From c5e9aa0040c4c3aa056f4dd925f9e72d8d269e6a Mon Sep 17 00:00:00 2001 From: Mike Gunderloy Date: Sun, 28 Dec 2008 20:31:33 -0600 Subject: Fix FCGI dispatching tests Signed-off-by: Pratik Naik --- railties/test/fcgi_dispatcher_test.rb | 49 +++++------------------------------ 1 file changed, 7 insertions(+), 42 deletions(-) (limited to 'railties') diff --git a/railties/test/fcgi_dispatcher_test.rb b/railties/test/fcgi_dispatcher_test.rb index cc054c24aa..c469c5dd01 100644 --- a/railties/test/fcgi_dispatcher_test.rb +++ b/railties/test/fcgi_dispatcher_test.rb @@ -1,10 +1,9 @@ require 'abstract_unit' begin +require 'action_controller' require 'fcgi_handler' -module ActionController; module Routing; module Routes; end end end - class RailsFCGIHandlerTest < Test::Unit::TestCase def setup @log = StringIO.new @@ -131,19 +130,11 @@ class RailsFCGIHandlerSignalsTest < Test::Unit::TestCase end end - class ::Dispatcher - class << self - attr_accessor :signal - alias_method :old_dispatch, :dispatch - def dispatch(cgi) - signal ? Process.kill(signal, $$) : old_dispatch - end - end - end - def setup @log = StringIO.new @handler = RailsFCGIHandler.new(@log) + @dispatcher = mock + Dispatcher.stubs(:new).returns(@dispatcher) end def test_interrupted_via_HUP_when_not_in_request @@ -159,19 +150,6 @@ class RailsFCGIHandlerSignalsTest < Test::Unit::TestCase assert_equal :reload, @handler.when_ready end - def test_interrupted_via_HUP_when_in_request - cgi = mock - FCGI.expects(:each_cgi).once.yields(cgi) - Dispatcher.expects(:signal).times(2).returns('HUP') - - @handler.expects(:reload!).once - @handler.expects(:close_connection).never - @handler.expects(:exit).never - - @handler.process! - assert_equal :reload, @handler.when_ready - end - def test_interrupted_via_USR1_when_not_in_request cgi = mock FCGI.expects(:each_cgi).once.yields(cgi) @@ -186,19 +164,6 @@ class RailsFCGIHandlerSignalsTest < Test::Unit::TestCase assert_nil @handler.when_ready end - def test_interrupted_via_USR1_when_in_request - cgi = mock - FCGI.expects(:each_cgi).once.yields(cgi) - Dispatcher.expects(:signal).times(2).returns('USR1') - - @handler.expects(:reload!).never - @handler.expects(:close_connection).with(cgi).once - @handler.expects(:exit).never - - @handler.process! - assert_equal :exit, @handler.when_ready - end - def test_restart_via_USR2_when_in_request cgi = mock FCGI.expects(:each_cgi).once.yields(cgi) @@ -217,7 +182,7 @@ class RailsFCGIHandlerSignalsTest < Test::Unit::TestCase def test_interrupted_via_TERM cgi = mock FCGI.expects(:each_cgi).once.yields(cgi) - Dispatcher.expects(:signal).times(2).returns('TERM') + ::Rack::Handler::FastCGI.expects(:serve).once.returns('TERM') @handler.expects(:reload!).never @handler.expects(:close_connection).never @@ -238,7 +203,7 @@ class RailsFCGIHandlerSignalsTest < Test::Unit::TestCase cgi = mock error = RuntimeError.new('foo') FCGI.expects(:each_cgi).once.yields(cgi) - Dispatcher.expects(:dispatch).once.with(cgi).raises(error) + ::Rack::Handler::FastCGI.expects(:serve).once.raises(error) @handler.expects(:dispatcher_error).with(error, regexp_matches(/^unhandled/)) @handler.process! end @@ -254,7 +219,7 @@ class RailsFCGIHandlerSignalsTest < Test::Unit::TestCase cgi = mock error = SignalException.new('USR2') FCGI.expects(:each_cgi).once.yields(cgi) - Dispatcher.expects(:dispatch).once.with(cgi).raises(error) + ::Rack::Handler::FastCGI.expects(:serve).once.raises(error) @handler.expects(:dispatcher_error).with(error, regexp_matches(/^stopping/)) @handler.process! end @@ -284,7 +249,7 @@ class RailsFCGIHandlerPeriodicGCTest < Test::Unit::TestCase cgi = mock FCGI.expects(:each_cgi).times(10).yields(cgi) - Dispatcher.expects(:dispatch).times(10).with(cgi) + Dispatcher.expects(:new).times(10) @handler.expects(:run_gc!).never 9.times { @handler.process! } -- cgit v1.2.3 From 860dd77006b66a0b0805e3e6edc6b80739f6fca3 Mon Sep 17 00:00:00 2001 From: Mike Gunderloy Date: Mon, 29 Dec 2008 08:00:30 -0600 Subject: Fix failing gem dependency tests [#1659 state:resolved] Signed-off-by: Pratik Naik --- railties/test/gem_dependency_test.rb | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) (limited to 'railties') diff --git a/railties/test/gem_dependency_test.rb b/railties/test/gem_dependency_test.rb index 30fd899fea..6c1f0961a1 100644 --- a/railties/test/gem_dependency_test.rb +++ b/railties/test/gem_dependency_test.rb @@ -9,33 +9,33 @@ Rails::VendorGemSourceIndex.silence_spec_warnings = true uses_mocha "Plugin Tests" do class GemDependencyTest < Test::Unit::TestCase def setup - @gem = Rails::GemDependency.new "hpricot" - @gem_with_source = Rails::GemDependency.new "hpricot", :source => "http://code.whytheluckystiff.net" - @gem_with_version = Rails::GemDependency.new "hpricot", :version => "= 0.6" - @gem_with_lib = Rails::GemDependency.new "aws-s3", :lib => "aws/s3" - @gem_without_load = Rails::GemDependency.new "hpricot", :lib => false + @gem = Rails::GemDependency.new "xhpricotx" + @gem_with_source = Rails::GemDependency.new "xhpricotx", :source => "http://code.whytheluckystiff.net" + @gem_with_version = Rails::GemDependency.new "xhpricotx", :version => "= 0.6" + @gem_with_lib = Rails::GemDependency.new "xaws-s3x", :lib => "aws/s3" + @gem_without_load = Rails::GemDependency.new "xhpricotx", :lib => false end def test_configuration_adds_gem_dependency config = Rails::Configuration.new - config.gem "aws-s3", :lib => "aws/s3", :version => "0.4.0" - assert_equal [["install", "aws-s3", "--version", '"= 0.4.0"']], config.gems.collect(&:install_command) + config.gem "xaws-s3x", :lib => "aws/s3", :version => "0.4.0" + assert_equal [["install", "xaws-s3x", "--version", '"= 0.4.0"']], config.gems.collect(&:install_command) end def test_gem_creates_install_command - assert_equal %w(install hpricot), @gem.install_command + assert_equal %w(install xhpricotx), @gem.install_command end def test_gem_with_source_creates_install_command - assert_equal %w(install hpricot --source http://code.whytheluckystiff.net), @gem_with_source.install_command + assert_equal %w(install xhpricotx --source http://code.whytheluckystiff.net), @gem_with_source.install_command end def test_gem_with_version_creates_install_command - assert_equal ["install", "hpricot", "--version", '"= 0.6"'], @gem_with_version.install_command + assert_equal ["install", "xhpricotx", "--version", '"= 0.6"'], @gem_with_version.install_command end def test_gem_creates_unpack_command - assert_equal %w(unpack hpricot), @gem.unpack_command + assert_equal %w(unpack xhpricotx), @gem.unpack_command end def test_gem_with_version_unpack_install_command @@ -43,7 +43,7 @@ uses_mocha "Plugin Tests" do mock_spec = mock() mock_spec.stubs(:version).returns('0.6') @gem_with_version.stubs(:specification).returns(mock_spec) - assert_equal ["unpack", "hpricot", "--version", '= 0.6'], @gem_with_version.unpack_command + assert_equal ["unpack", "xhpricotx", "--version", '= 0.6'], @gem_with_version.unpack_command end def test_gem_adds_load_paths -- cgit v1.2.3 From ab7c25d51174779547ab74bcd23e40204891e370 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 29 Dec 2008 19:27:19 -0600 Subject: Clean up view path cruft and split path implementations into Template::Path and Template::EagerPath --- railties/lib/initializer.rb | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'railties') diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb index 637fe74313..10c2490624 100644 --- a/railties/lib/initializer.rb +++ b/railties/lib/initializer.rb @@ -370,8 +370,9 @@ Run `rake gems:install` to install the missing gems. def load_view_paths if configuration.frameworks.include?(:action_view) if configuration.cache_classes - ActionController::Base.view_paths.load if configuration.frameworks.include?(:action_controller) - ActionMailer::Base.template_root.load if configuration.frameworks.include?(:action_mailer) + view_path = ActionView::Template::EagerPath.new(configuration.view_path) + ActionController::Base.view_paths = view_path if configuration.frameworks.include?(:action_controller) + ActionMailer::Base.template_root = view_path if configuration.frameworks.include?(:action_mailer) end end end @@ -473,7 +474,7 @@ Run `rake gems:install` to install the missing gems. # set to use Configuration#view_path. def initialize_framework_views if configuration.frameworks.include?(:action_view) - view_path = ActionView::PathSet::Path.new(configuration.view_path, false) + view_path = ActionView::Template::Path.new(configuration.view_path) ActionMailer::Base.template_root ||= view_path if configuration.frameworks.include?(:action_mailer) ActionController::Base.view_paths = view_path if configuration.frameworks.include?(:action_controller) && ActionController::Base.view_paths.empty? end -- cgit v1.2.3 From 724151d8814fe1ff2351e8c70b0fb02512666e96 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 30 Dec 2008 12:44:31 -0800 Subject: Clean trailing / after rails root from backtraces --- railties/lib/rails/backtrace_cleaner.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties') diff --git a/railties/lib/rails/backtrace_cleaner.rb b/railties/lib/rails/backtrace_cleaner.rb index 94d34cda39..ee67255289 100644 --- a/railties/lib/rails/backtrace_cleaner.rb +++ b/railties/lib/rails/backtrace_cleaner.rb @@ -15,7 +15,7 @@ module Rails def initialize super - add_filter { |line| line.sub(RAILS_ROOT, '') } + add_filter { |line| line.sub("#{RAILS_ROOT}/", '') } add_filter { |line| line.sub(ERB_METHOD_SIG, '') } add_filter { |line| line.sub('./', '/') } # for tests add_filter { |line| line.sub(/(#{GEMS_DIR})\/gems\/([a-z]+)-([0-9.]+)\/(.*)/, '\2 (\3) \4')} # http://gist.github.com/30430 -- cgit v1.2.3 From 42b32938d99d8f930e3020659ec0619aa5205c05 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 30 Dec 2008 18:25:44 -0800 Subject: Only silence backtrace from plugin lib dirs --- railties/lib/rails/backtrace_cleaner.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'railties') diff --git a/railties/lib/rails/backtrace_cleaner.rb b/railties/lib/rails/backtrace_cleaner.rb index ee67255289..e1b422716d 100644 --- a/railties/lib/rails/backtrace_cleaner.rb +++ b/railties/lib/rails/backtrace_cleaner.rb @@ -2,7 +2,7 @@ module Rails class BacktraceCleaner < ActiveSupport::BacktraceCleaner ERB_METHOD_SIG = /:in `_run_erb_.*/ - VENDOR_DIRS = %w( vendor/plugins vendor/gems vendor/rails ) + VENDOR_DIRS = %w( vendor/gems vendor/rails ) SERVER_DIRS = %w( lib/mongrel bin/mongrel lib/passenger bin/passenger-spawn-server lib/rack ) @@ -20,6 +20,7 @@ module Rails add_filter { |line| line.sub('./', '/') } # for tests add_filter { |line| line.sub(/(#{GEMS_DIR})\/gems\/([a-z]+)-([0-9.]+)\/(.*)/, '\2 (\3) \4')} # http://gist.github.com/30430 add_silencer { |line| ALL_NOISE.any? { |dir| line.include?(dir) } } + add_silencer { |line| line =~ %r(vendor/plugins/[^\/]+/lib) } end end -- cgit v1.2.3 From a38c749d8b5fd020d7294ffb4d597d4ab3fb30db Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Fri, 2 Jan 2009 22:16:48 -0800 Subject: Sync 'rails/rails/master' --- railties/test/console_app_test.rb | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'railties') diff --git a/railties/test/console_app_test.rb b/railties/test/console_app_test.rb index cbaf230594..f419fe0d8d 100644 --- a/railties/test/console_app_test.rb +++ b/railties/test/console_app_test.rb @@ -14,6 +14,15 @@ require 'console_app' Test::Unit.run = false class ConsoleAppTest < Test::Unit::TestCase + def test_app_method_should_return_integration_session + assert_nothing_thrown do + console_session = app + assert_not_nil console_session + assert_instance_of ActionController::Integration::Session, + console_session + end + end + uses_mocha 'console reload test' do def test_reload_should_fire_preparation_callbacks a = b = c = nil -- cgit v1.2.3 From ca54cc5df72a8bd7660d5be8333dcee2b6949257 Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Sun, 4 Jan 2009 00:56:52 -0800 Subject: Sync 'rails/rails/master' --- railties/lib/initializer.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties') diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb index 10c2490624..619701460d 100644 --- a/railties/lib/initializer.rb +++ b/railties/lib/initializer.rb @@ -537,7 +537,7 @@ Run `rake gems:install` to install the missing gems. end def initialize_metal - configuration.middleware.use Rails::Rack::Metal + configuration.middleware.insert_before(:"ActionController::VerbPiggybacking", Rails::Rack::Metal) end # Initializes framework-specific settings for each of the loaded frameworks -- cgit v1.2.3 From cf09fa74f7a9d9895b9a2d0fc475864d7e4bb56e Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 7 Jan 2009 13:23:10 -0800 Subject: Include process methods in ActionController::TestCase only. No need to alias_method_chain :process either. --- railties/lib/test_help.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties') diff --git a/railties/lib/test_help.rb b/railties/lib/test_help.rb index 93ba1bc216..ee24ea3a45 100644 --- a/railties/lib/test_help.rb +++ b/railties/lib/test_help.rb @@ -3,7 +3,7 @@ silence_warnings { RAILS_ENV = "test" } require 'test/unit' -require 'action_controller/test_process' +require 'action_controller/test_case' require 'action_view/test_case' require 'action_controller/integration' require 'action_mailer/test_case' if defined?(ActionMailer) -- cgit v1.2.3 From bb03719943ee5f8e357323f35aa7ffd083938fc2 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 7 Jan 2009 16:37:32 -0800 Subject: Fix test broken by test process changes --- railties/test/error_page_test.rb | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) (limited to 'railties') diff --git a/railties/test/error_page_test.rb b/railties/test/error_page_test.rb index 844f889aad..f819e468e8 100644 --- a/railties/test/error_page_test.rb +++ b/railties/test/error_page_test.rb @@ -1,6 +1,6 @@ require 'abstract_unit' require 'action_controller' -require 'action_controller/test_process' +require 'action_controller/test_case' RAILS_ENV = "test" CURRENT_DIR = File.expand_path(File.dirname(__FILE__)) @@ -22,13 +22,10 @@ ActionController::Routing::Routes.draw do |map| map.connect ':controller/:action/:id' end -class ErrorPageControllerTest < Test::Unit::TestCase +class ErrorPageControllerTest < ActionController::TestCase def setup - @controller = ErrorPageController.new - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - ActionController::Base.consider_all_requests_local = false + rescue_action_in_public! end def test_500_error_page_instructs_system_administrator_to_check_log_file @@ -38,6 +35,6 @@ class ErrorPageControllerTest < Test::Unit::TestCase end get :crash expected_log_file = "#{RAILS_ENV}.log" - assert_not_nil @response.body.index(expected_log_file) + assert_not_nil @response.body.index(expected_log_file), @response.body end end -- cgit v1.2.3 From a0f2b1d95d3785de92ae271fd7ea23e91c0cadc6 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Tue, 27 Jan 2009 18:17:39 -0600 Subject: Reorganize ActionController folder structure --- railties/lib/dispatcher.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties') diff --git a/railties/lib/dispatcher.rb b/railties/lib/dispatcher.rb index 9f8b59aa3d..7f9a6221d9 100644 --- a/railties/lib/dispatcher.rb +++ b/railties/lib/dispatcher.rb @@ -20,5 +20,5 @@ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #++ -require 'action_controller/dispatcher' +require 'action_controller/dispatch/dispatcher' Dispatcher = ActionController::Dispatcher -- cgit v1.2.3 From d4a817c066ec66ab6f44958a3e10619f952b77e8 Mon Sep 17 00:00:00 2001 From: Yehuda Katz Date: Mon, 2 Feb 2009 14:01:29 -0800 Subject: Make tests pass --- railties/test/error_page_test.rb | 2 +- railties/test/rails_info_controller_test.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'railties') diff --git a/railties/test/error_page_test.rb b/railties/test/error_page_test.rb index f819e468e8..c0e8fe1ee0 100644 --- a/railties/test/error_page_test.rb +++ b/railties/test/error_page_test.rb @@ -1,6 +1,6 @@ require 'abstract_unit' require 'action_controller' -require 'action_controller/test_case' +require 'action_controller/testing/test_case' RAILS_ENV = "test" CURRENT_DIR = File.expand_path(File.dirname(__FILE__)) diff --git a/railties/test/rails_info_controller_test.rb b/railties/test/rails_info_controller_test.rb index e274e1aa6e..b63cd00ba5 100644 --- a/railties/test/rails_info_controller_test.rb +++ b/railties/test/rails_info_controller_test.rb @@ -1,6 +1,6 @@ require 'abstract_unit' require 'action_controller' -require 'action_controller/test_process' +require 'action_controller/testing/process' module Rails; end require 'rails/info' -- cgit v1.2.3 From f97832b1e4406a76d268a96b521d2297adec0ae3 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Tue, 24 Mar 2009 12:15:43 +0000 Subject: Merge docrails --- railties/Rakefile | 1 + railties/guides/images/fxn.jpg | Bin 17868 -> 17773 bytes railties/guides/rails_guides.rb | 1 + railties/guides/rails_guides/generator.rb | 34 +++++++++++++++++++++ railties/guides/rails_guides/levenshtein.rb | 29 ++++++++++++++++++ .../guides/source/active_record_querying.textile | 1 - railties/guides/source/form_helpers.textile | 2 +- .../guides/source/layouts_and_rendering.textile | 2 +- 8 files changed, 67 insertions(+), 3 deletions(-) create mode 100644 railties/guides/rails_guides/levenshtein.rb (limited to 'railties') diff --git a/railties/Rakefile b/railties/Rakefile index 6c0fc22629..a9adbda0b5 100644 --- a/railties/Rakefile +++ b/railties/Rakefile @@ -247,6 +247,7 @@ end desc 'Generate guides (for authors), use ONLY=foo to process just "foo.textile"' task :guides do + ENV["WARN_BROKEN_LINKS"] = "1" # authors can't disable this ruby "guides/rails_guides.rb" end diff --git a/railties/guides/images/fxn.jpg b/railties/guides/images/fxn.jpg index b661a0e402..81999341f1 100644 Binary files a/railties/guides/images/fxn.jpg and b/railties/guides/images/fxn.jpg differ diff --git a/railties/guides/rails_guides.rb b/railties/guides/rails_guides.rb index b73e10e43f..e0532812e4 100644 --- a/railties/guides/rails_guides.rb +++ b/railties/guides/rails_guides.rb @@ -33,6 +33,7 @@ module RailsGuides autoload :Indexer, "rails_guides/indexer" autoload :Helpers, "rails_guides/helpers" autoload :TextileExtensions, "rails_guides/textile_extensions" + autoload :Levenshtein, "rails_guides/levenshtein" end RedCloth.send(:include, RailsGuides::TextileExtensions) diff --git a/railties/guides/rails_guides/generator.rb b/railties/guides/rails_guides/generator.rb index 6c0d9f3c3b..f93282db2e 100644 --- a/railties/guides/rails_guides/generator.rb +++ b/railties/guides/rails_guides/generator.rb @@ -57,6 +57,7 @@ module RailsGuides result = view.render(:layout => 'layout', :text => textile(body)) f.write result + warn_about_broken_links(result) if ENV.key?("WARN_BROKEN_LINKS") end end end @@ -134,5 +135,38 @@ module RailsGuides code_blocks[$1.to_i] end 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(/ 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/levenshtein.rb b/railties/guides/rails_guides/levenshtein.rb new file mode 100644 index 0000000000..4010b61e26 --- /dev/null +++ b/railties/guides/rails_guides/levenshtein.rb @@ -0,0 +1,29 @@ +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 diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index 442521cbf4..b112c4f5fb 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -111,7 +111,6 @@ h5. +last+ Model.last(options = nil) finds the last record matched by the supplied options. If no +options+ are supplied, the last matching record is returned. For example: -# Find the client with primary key (id) 10. client = Client.last => # "Russel"> diff --git a/railties/guides/source/form_helpers.textile b/railties/guides/source/form_helpers.textile index 9ab4deff4e..22d24b0903 100644 --- a/railties/guides/source/form_helpers.textile +++ b/railties/guides/source/form_helpers.textile @@ -683,7 +683,7 @@ This would result in +params[:addresses]+ being an array of hashes with keys +li 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 a second 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. +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 diff --git a/railties/guides/source/layouts_and_rendering.textile b/railties/guides/source/layouts_and_rendering.textile index 69faa1b449..809d2b2172 100644 --- a/railties/guides/source/layouts_and_rendering.textile +++ b/railties/guides/source/layouts_and_rendering.textile @@ -959,7 +959,7 @@ On pages generated by +NewsController+, you want to hide the top menu and add a
Right menu items here
<%= yield(:news_content) or yield %> <% end -%> -<% render :file => 'layouts/application' %> +<%= render :file => 'layouts/application' %> That's it. The News views will use the new layout, hiding the top menu and adding a new right menu inside the "content" div. -- cgit v1.2.3 From cad3e8b261a8d9551bc19a57007acf574d957548 Mon Sep 17 00:00:00 2001 From: Michael Schuerig Date: Thu, 2 Apr 2009 11:54:52 -0500 Subject: Show installed middleware in builtin rails info (/rails/info/properties) [#2396 state:resolved] Signed-off-by: Joshua Peek --- railties/builtin/rails_info/rails/info.rb | 11 ++++++++++- railties/html/index.html | 7 ++++++- 2 files changed, 16 insertions(+), 2 deletions(-) (limited to 'railties') diff --git a/railties/builtin/rails_info/rails/info.rb b/railties/builtin/rails_info/rails/info.rb index a20d9bfe62..0dd1c090c1 100644 --- a/railties/builtin/rails_info/rails/info.rb +++ b/railties/builtin/rails_info/rails/info.rb @@ -56,7 +56,12 @@ module Rails returning table = '' do properties.each do |(name, value)| table << %() - table << %() + formatted_value = if value.kind_of?(Array) + "
    " + value.map { |v| "
  • #{CGI.escapeHTML(v.to_s)}
  • " }.join + "
" + else + CGI.escapeHTML(value.to_s) + end + table << %() end table << '
#{CGI.escapeHTML(name.to_s)}#{CGI.escapeHTML(value.to_s)}
#{formatted_value}
' end @@ -102,6 +107,10 @@ module Rails end end + property 'Middleware' do + ActionController::Dispatcher.middleware.active.map(&:inspect) + end + # The Rails Git revision, if it's checked out into vendor/rails. property 'Edge Rails revision' do edge_rails_revision diff --git a/railties/html/index.html b/railties/html/index.html index 0dd5189fb7..cd337dc74c 100644 --- a/railties/html/index.html +++ b/railties/html/index.html @@ -99,7 +99,12 @@ } #about-content td.name {color: #555} #about-content td.value {color: #000} - + + #about-content ul { + padding: 0; + list-style-type: none; + } + #about-content.failure { background-color: #fcc; border: 1px solid #f00; -- cgit v1.2.3 From 632bbbfe1cc49ab92c6de858865ffcdcfa67635f Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Sat, 4 Apr 2009 17:33:36 +0100 Subject: Merge docrails --- .../configs/initializers/backtrace_silencers.rb | 2 +- railties/guides/source/2_3_release_notes.textile | 2 +- railties/guides/source/caching_with_rails.textile | 246 ++++++++++----------- railties/guides/source/getting_started.textile | 4 +- railties/guides/source/rails_on_rack.textile | 34 +-- railties/guides/source/routing.textile | 6 +- 6 files changed, 143 insertions(+), 151 deletions(-) (limited to 'railties') diff --git a/railties/configs/initializers/backtrace_silencers.rb b/railties/configs/initializers/backtrace_silencers.rb index c2169ed01c..839d4cde19 100644 --- a/railties/configs/initializers/backtrace_silencers.rb +++ b/railties/configs/initializers/backtrace_silencers.rb @@ -3,5 +3,5 @@ # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } -# You can also remove all the silencers if you're trying do debug a problem that might steem from framework code. +# 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! \ No newline at end of file diff --git a/railties/guides/source/2_3_release_notes.textile b/railties/guides/source/2_3_release_notes.textile index cc2e2dc20c..6a97fd2cd1 100644 --- a/railties/guides/source/2_3_release_notes.textile +++ b/railties/guides/source/2_3_release_notes.textile @@ -32,7 +32,7 @@ Here's a summary of the rack-related changes: * +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 => "..." }+. +* 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. diff --git a/railties/guides/source/caching_with_rails.textile b/railties/guides/source/caching_with_rails.textile index 5c55538283..f1ad7b820d 100644 --- a/railties/guides/source/caching_with_rails.textile +++ b/railties/guides/source/caching_with_rails.textile @@ -18,9 +18,11 @@ 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 get started make sure +config.action_controller.perform_caching+ is set -to +true+ for your environment. This flag is normally set in the -corresponding config/environments/*.rb. By default, caching is disabled for development and test, and enabled for production. +To start playing with testing 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. config.action_controller.perform_caching = true @@ -29,51 +31,56 @@ config.action_controller.perform_caching = true h4. Page Caching Page caching is a Rails mechanism which allows the request for a generated -page to be fulfilled by the webserver, without ever having to go through the +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. -So, how do you enable this super-fast cache behavior? Suppose you +So, how do you enable this super-fast cache behavior? Simple, let's say you have a controller called +ProductsController+ and an +index+ action that lists all -the products. You could enable caching for this action like this: +the products class ProductsController < ActionController caches_page :index - def index; end + def index + @products = Products.all + end end -The first time anyone requests products/index, Rails will generate a file -called +index.html+. If a web server see this file, it will be served in response to the -next request for products/index, without your Rails application being called. +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 +File.join(self.root, "public")+ - that is, the public directory under your Rails application's root). This can be configured by +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 +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 +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. This can be configured by changing 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 you could extend the products controller like this: +In order to expire this page when a new product is added we could extend our +example controller like this: class ProductsController < ActionController caches_page :index - def index; end + def index + @products = Products.all + end def create expire_page :action => :index @@ -85,45 +92,42 @@ end If you want a more complicated expiration scheme, you can use cache sweepers to expire cached objects when things change. This is covered in the section on Sweepers. -Note: Page caching ignores all parameters, so /products/list?page=1 will be written out to the filesystem as /products/list.html and if someone requests /products/list?page=2, they will be returned the same result as page=1. Be careful when page caching GET parameters in the URL! +Note: Page caching ignores all parameters. For example +/products?page=1+ will be written out to the filesystem as +products.html+ with no reference to the +page+ parameter. Thus, if someone requests +/products?page=2+ later, they will get the cached first page. Be careful when page caching GET parameters in the URL! h4. Action Caching -One of the issues with page caching is that you cannot use it for pages that -require checking code to determine whether the user should be permitted access. 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 web server to the Rails stack and Action Pack so -that before filters can be run on it before the cache is served. This allows you to use -authentication and other restrictions while still serving the +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. +Clearing the cache works in the exact same way as with Page Caching. -Let's say you only wanted authenticated users to edit or create a Product -object, but still cache those pages: +Let's say you only wanted authenticated users to call actions on +ProductsController+. class ProductsController < ActionController - before_filter :authenticate, :only => [ :edit, :create ] - caches_page :index - caches_action :edit + before_filter :authenticate + caches_action :index - def index; end + def index + @products = Product.all + end def create - expire_page :action => :index - expire_action :action => :edit + expire_action :action => :index end - def edit; end - end 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 the name of the logged-in user +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. @@ -149,7 +153,7 @@ 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 +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: @@ -160,35 +164,33 @@ could use this piece of code: <% cache do %> All available products: - <% Product.find(:all).each do |p| %> + <% Product.all.each do |p| %> <%= link_to p.name, product_url(p) %> <% end %> <% end %> The cache block in our example will bind to the action that called it and is -written out to the same place as the action cache, which means that if you +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: -<% cache(:action => 'recent', :action_suffix => 'all_prods') do %> +<% cache(:action => 'recent', :action_suffix => 'all_products') do %> All available products: -You can expire the cache using the +expire_fragment+ method, like so: +and you can expire it using the +expire_fragment+ method, like so: -expire_fragment(:controller => 'products', :action => 'recent', - :action_suffix => 'all_prods) +expire_fragment(:controller => 'products', :action => 'recent', :action_suffix => 'all_products') -If you don't want the cache block to bind to the action that called it, you can -also use globally keyed fragments. To do this, call the +cache+ method with a key, like +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: -<% cache(:key => - ['all_available_products', @latest_product.created_at].join(':')) do %> +<% cache('all_available_products') do %> All available products: <% end %> @@ -197,16 +199,15 @@ This fragment is then available to all actions in the +ProductsController+ using the key and can be expired the same way: -expire_fragment(:key => - ['all_available_products', @latest_product.created_at].join(':')) +expire_fragment('all_available_products') 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 na +ActionController::Caching::Sweeper+ -class. This class is an Observer that looks for changes to an object via callbacks, ++expire_{page,action,fragment}+ calls in your code. It does this by moving all the work +required to expire cached content into a +ActionController::Caching::Sweeper+ +class. 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. @@ -214,9 +215,8 @@ Continuing with our Product controller example, we could rewrite it with a sweeper like this: -class StoreSweeper < ActionController::Caching::Sweeper - # This sweeper is going to keep an eye on the Product model - observe Product +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) @@ -234,91 +234,82 @@ class StoreSweeper < ActionController::Caching::Sweeper end private - def expire_cache_for(record) - # Expire the list page now that we added a new product - expire_page(:controller => '#{record}', :action => 'list') + 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(:controller => '#{record}', - :action => 'recent', :action_suffix => 'all_products') + expire_fragment('all_available_products') end end -The sweeper has to be added to the controller that will use it. So, if we wanted to expire the cached content for the +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 a expire method +which specifies the page we want to expire: + + + expire_action(:controller => 'products', :action => 'edit', :id => product) + + +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: class ProductsController < ActionController - before_filter :authenticate, :only => [ :edit, :create ] - caches_page :list - caches_action :edit - cache_sweeper :store_sweeper, :only => [ :create ] - - def list; end + before_filter :authenticate + caches_action :index + cache_sweeper :product_sweeper - def create - expire_page :action => :list - expire_action :action => :edit + def index + @products = Product.all end - def edit; end - end h4. SQL Caching Query caching is a Rails feature that caches the result set returned by each -query. If Rails encounters the same query again during the current request, it +query so that if Rails encounters the same query again for that request, it will used the cached result set as opposed to running the query against the -database. +database again. For example: class ProductsController < ActionController - before_filter :authenticate, :only => [ :edit, :create ] - caches_page :list - caches_action :edit - cache_sweeper :store_sweeper, :only => [ :create ] - - def list + def index # Run a find query - Product.find(:all) + @products = Product.all ... # Run the same query again - Product.find(:all) - end - - def create - expire_page :action => :list - expire_action :action => :edit + @products = Product.all end - def edit; end - end -In the 'list' action above, the result set returned by the first -Product.find(:all) will be cached and will be used to avoid querying the -database again the second time that finder is called. +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. -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. +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. -h4. Cache Stores +h4. Cache stores Rails (as of 2.1) provides different stores for the cached data created by action and fragment caches. Page caches are always stored on disk. -Rails 2.1 and above provide ActiveSupport::Cache::Store which can be used to +Rails 2.1 and above provide +ActiveSupport::Cache::Store+ which can be used to cache strings. Some cache store implementations, like MemoryStore, are able to cache arbitrary Ruby objects, but don't count on every cache store to be able to do that. @@ -344,12 +335,13 @@ need thread-safety. ActionController::Base.cache_store = :memory_store -2) ActiveSupport::Cache::FileStore: Cached data is stored on the disk. This is +2) ActiveSupport::Cache::FileStore: Cached data is stored on the disk, this is the default store and the default path for this store is: /tmp/cache. Works well for all types of environments and allows all processes running from the same application directory to access the cached content. If /tmp/cache does not exist, the default store becomes MemoryStore. + ActionController::Base.cache_store = :file_store, "/path/to/cache/directory" @@ -359,6 +351,7 @@ DRb process that all servers communicate with. This works for all environments and only keeps one cache around for all processes, but requires that you run and manage a separate DRb process. + ActionController::Base.cache_store = :drb_store, "druby://localhost:9192" @@ -368,28 +361,26 @@ Rails uses the bundled memcached-client gem by default. This is currently the most popular cache store for production websites. Special features: - -* Clustering and load balancing. One can specify multiple memcached servers, + * Clustering and load balancing. One can specify multiple memcached servers, and MemCacheStore will load balance between all available servers. If a server goes down, then MemCacheStore will ignore it until it goes back online. -* Time-based expiry support. See +write+ and the +:expires_in+ option. -* Per-request in memory cache for all communication with the MemCache server(s). + * Time-based expiry support. See +write+ and the +:expires_in+ option. + * Per-request in memory cache for all communication with the MemCache server(s). It also accepts a hash of additional options: -* +:namespace+- specifies a string that will automatically be prepended to keys when accessing the memcached store. -* +:readonly+- a boolean value that when set to true will make the store read-only, with an error raised on any attempt to write. -* +:multithread+ - a boolean value that adds thread safety to read/write operations - it is unlikely you'll need to use this option as the Rails threadsafe! method offers the same functionality. + * +:namespace+- specifies a string that will automatically be prepended to keys when accessing the memcached store. + * +:readonly+- a boolean value that when set to true will make the store read-only, with an error raised on any attempt to write. + * +:multithread+ - a boolean value that adds thread safety to read/write operations - it is unlikely you'll need to use this option as the Rails threadsafe! method offers the same functionality. The read and write methods of the MemCacheStore accept an options hash too. -When reading you can specify +:raw => true+ to prevent the object being -marshaled +When reading you can specify +:raw => true+ to prevent the object being marshaled (by default this is false which means the raw value in the cache is passed to +Marshal.load+ before being returned to you.) -When writing to the cache it is also possible to specify +:raw => true+. This means -that the value is not passed to +Marshal.dump+ before being stored in the cache (by +When writing to the cache it is also possible to specify +:raw => true+ means +the value is not passed to +Marshal.dump+ before being stored in the cache (by default this is false). The write method also accepts an +:unless_exist+ flag which determines whether @@ -424,15 +415,14 @@ ActionController::Base.cache_store = :compressed_mem_cache_store, "localhost" ActionController::Base.cache_store = MyOwnStore.new("parameter") -NOTE: +config.cache_store+ can be used in place of -+ActionController::Base.cache_store+ in the +Rails::Initializer.run+ block in -environment.rb. ++Note: +config.cache_store+ can be used in place of ++ActionController::Base.cache_store+ in your +Rails::Initializer.run+ block in ++environment.rb+ In addition to all of this, Rails also adds the +ActiveRecord::Base#cache_key+ -method that generates a key using the class name, id and updated_at timestamp -(if available). +method that generates a key using the class name, +id+ and +updated_at+ timestamp (if available). -An example: +You can access these cache stores at a low level for storing queries and other objects. Here's an example: Rails.cache.read("city") # => nil @@ -440,18 +430,18 @@ Rails.cache.write("city", "Duckburgh") Rails.cache.read("city") # => "Duckburgh" -h3. Conditional GET Support +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. +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 @@ -509,16 +499,18 @@ Also the new "Cache money":http://github.com/nkallen/cache-money/tree/master plu h3. References +* "Scaling Rails Screencasts":http://railslab.newrelic.com/scaling-rails * "RailsEnvy, Rails Caching Tutorial, Part 1":http://www.railsenvy.com/2007/2/28/rails-caching-tutorial * "RailsEnvy, Rails Caching Tutorial, Part 1":http://www.railsenvy.com/2007/3/20/ruby-on-rails-caching-tutorial-part-2 * "ActiveSupport::Cache documentation":http://api.rubyonrails.org/classes/ActiveSupport/Cache.html * "Rails 2.1 integrated caching tutorial":http://thewebfellas.com/blog/2008/6/9/rails-2-1-now-with-better-integrated-caching -h3. Changelog +h3. Changelog "Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/10-guide-to-caching -* February 22, 2009: Beefed up the section on cache_stores -* December 27, 2008: Typo fixes -* November 23, 2008: Incremental updates with various suggested changes and formatting cleanup -* September 15, 2008: Initial version by Aditya Chadha +April 1, 2009: Made a bunch of small fixes +February 22, 2009: Beefed up the section on cache_stores +December 27, 2008: Typo fixes +November 23, 2008: Incremental updates with various suggested changes and formatting cleanup +September 15, 2008: Initial version by Aditya Chadha diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile index 97f141b5e9..a216201490 100644 --- a/railties/guides/source/getting_started.textile +++ b/railties/guides/source/getting_started.textile @@ -312,7 +312,7 @@ Now if you navigate to +http://localhost:3000+ in your browser, you'll see the + NOTE. For more information about routing, refer to "Rails Routing from the Outside In":routing.html. -h3. Getting Up and Running Quickly With Scaffolding +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. @@ -474,7 +474,7 @@ This code sets the +@posts+ instance variable to an array of all posts in the da TIP: For more information on finding records with Active Record, see "Active Record Query Interface":active_record_querying.html. -The +respond_to+ block handles both HTML and XML calls to this action. If you browse to +http://localhost:3000/posts.xml+, you'll see all of the posts in XML format. The HTML format looks for a view in +app/views/posts/+ with a name that corresponds to the action name. Rails makes all of the instance variables from the action available to the view. Here's +app/view/posts/index.html.erb+: +The +respond_to+ block handles both HTML and XML calls to this action. If you browse to +http://localhost:3000/posts.xml+, you'll see all of the posts in XML format. The HTML format looks for a view in +app/views/posts/+ with a name that corresponds to the action name. Rails makes all of the instance variables from the action available to the view. Here's +app/views/posts/index.html.erb+:

Listing posts

diff --git a/railties/guides/source/rails_on_rack.textile b/railties/guides/source/rails_on_rack.textile index 07ca1624f4..05581f943f 100644 --- a/railties/guides/source/rails_on_rack.textile +++ b/railties/guides/source/rails_on_rack.textile @@ -9,7 +9,7 @@ This guide covers Rails integration with Rack and interfacing with other Rack co endprologue. -WARNING: This guide assumes a working knowledge of Rack protocol and Rack concepts such as middlewares, url maps and Rack::Builder. +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 @@ -51,9 +51,9 @@ app = Rack::Builder.new { Middlewares used in the code above are primarily useful only in the development envrionment. The following table explains their usage: |_.Middleware|_.Purpose| -|Rails::Rack::LogTailer|Appends log file output to console| -|Rails::Rack::Static|Serves static files inside +RAILS_ROOT/public+ directory| -|Rails::Rack::Debugger|Starts Debugger| +|+Rails::Rack::LogTailer+|Appends log file output to console| +|+Rails::Rack::Static+|Serves static files inside +RAILS_ROOT/public+ directory| +|+Rails::Rack::Debugger+|Starts Debugger| h4. +rackup+ @@ -109,7 +109,7 @@ use ActiveRecord::QueryCache run ActionController::Dispatcher.new -Purpose of each of this middlewares is explained in "Internal Middlewares":#internal-middleware-stack section. +Purpose of each of this middlewares is explained in the "Internal Middlewares":#internal-middleware-stack section. h4. Configuring Middleware Stack @@ -128,7 +128,7 @@ You can add a new middleware to the middleware stack using any of the following Example: -# environment.rb +# config/environment.rb # Push Rack::BounceFavicon at the bottom config.middleware.use Rack::BounceFavicon @@ -145,7 +145,7 @@ You can swap an existing middleware in the middleware stack using +config.middle Example: -# environment.rb +# config/environment.rb # Replace ActionController::Failsafe with Lifo::Failsafe config.middleware.swap ActionController::Failsafe, Lifo::Failsafe @@ -166,14 +166,14 @@ 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 +env["rack.multithread"]+ flag to +true+ and wraps the application within a Mutex.| -|ActionController::Failsafe|Returns HTTP Status +500+ to the client if an exception gets raised while dispatching.| -|ActiveRecord::QueryCache|Enable the Active Record query cache.| -|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 +env["HTTP_X_HTTP_METHOD_OVERRIDE"]+.| -|Rack::Head|Discards the response body if the client sends a +HEAD+ request.| +|+Rack::Lock+|Sets +env["rack.multithread"]+ flag to +true+ and wraps the application within a Mutex.| +|+ActionController::Failsafe+|Returns HTTP Status +500+ to the client if an exception gets raised while dispatching.| +|+ActiveRecord::QueryCache+|Enable the Active Record query cache.| +|+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 +env["HTTP_X_HTTP_METHOD_OVERRIDE"]+.| +|+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. @@ -229,7 +229,7 @@ h3. Rails Metal Applications Rails Metal applications are minimal Rack applications specially designed for integrating with a typical Rails application. As Rails Metal Applications skip all of the Action Controller stack, serving a request has no overhead from the Rails framework itself. This is especially useful for infrequent cases where the performance of the full stack Rails framework is an issue. -Ryan Bates' railscast on the "Rails Metal":http://railscasts.com/episodes/150-rails-metal provides a nice walkthrough generating and using Rails Metal. +Ryan Bates' "railscast on Rails Metal":http://railscasts.com/episodes/150-rails-metal provides a nice walkthrough generating and using Rails Metal. h4. Generating a Metal Application @@ -256,7 +256,7 @@ class Poller end -Metal applications within +app/metal+ folders in plugins will also be discovered and added to the list +Metal applications within +app/metal+ folders in plugins will also be discovered and added to the list. Metal applications are an optimization. You should make sure to "understand the related performance implications":http://weblog.rubyonrails.org/2008/12/20/performance-of-rails-metal before using it. diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile index a4d9e140d5..e9adb4b308 100644 --- a/railties/guides/source/routing.textile +++ b/railties/guides/source/routing.textile @@ -582,7 +582,7 @@ To add a member route, use the +:member+ option: map.resources :photos, :member => { :preview => :get } -This will enable Rails to recognize URLs such as +/photos/1/preview+ using the GET HTTP verb, and route them to the preview action of the Photos controller. It will also create a +preview_photo+ route helper. +This will enable Rails to recognize URLs such as +/photos/1/preview+ using the GET HTTP verb, and route them to the preview action of the Photos controller. It will also create the +preview_photo_url+ and +preview_photo_path+ route helpers. Within the hash of member routes, each route name specifies the HTTP verb that it will recognize. You can use +:get+, +:put+, +:post+, +:delete+, or +:any+ here. You can also specify an array of methods, if you need more than one but you don't want to allow just anything: @@ -598,7 +598,7 @@ To add a collection route, use the +:collection+ option: map.resources :photos, :collection => { :search => :get } -This will enable Rails to recognize URLs such as +/photos/search+ using the GET HTTP verb, and route them to the search action of the Photos controller. It will also create a +search_photos+ route helper. +This will enable Rails to recognize URLs such as +/photos/search+ using the GET HTTP verb, and route them to the search action of the Photos controller. It will also create the +search_photos_url+ and +search_photos_path+ route helpers. Just as with member routes, you can specify an array of methods for a collection route: @@ -614,7 +614,7 @@ To add a new route (one that creates a new resource), use the +:new+ option: map.resources :photos, :new => { :upload => :post } -This will enable Rails to recognize URLs such as +/photos/upload+ using the POST HTTP verb, and route them to the upload action of the Photos controller. It will also create a +upload_photos+ route helper. +This will enable Rails to recognize URLs such as +/photos/upload+ using the POST HTTP verb, and route them to the upload action of the Photos controller. It will also create the +upload_photos_path+ and +upload_photos_url+ route helpers. TIP: If you want to redefine the verbs accepted by one of the standard actions, you can do so by explicitly mapping that action. For example:
+map.resources :photos, :new => { :new => :any }+
This will allow the new action to be invoked by any request to +photos/new+, no matter what HTTP verb you use. -- cgit v1.2.3 From f209d3898fbd866e1405861319b85c97674a0508 Mon Sep 17 00:00:00 2001 From: Manfred Stienstra Date: Tue, 7 Apr 2009 09:16:48 -0500 Subject: Improve tests and code for Rails::InfoController and Rails::Info [#2411 state:resolved] - Refactor Rails::InfoController tests. - Return forbidden status from the InfoController for remote requests instead of a 500. - Add tests for displaying middleware in Rails::Info. Signed-off-by: Joshua Peek --- .../builtin/rails_info/rails/info_controller.rb | 2 +- railties/test/rails_info_controller_test.rb | 54 ++++++++++------------ railties/test/rails_info_test.rb | 17 ++++++- 3 files changed, 41 insertions(+), 32 deletions(-) (limited to 'railties') diff --git a/railties/builtin/rails_info/rails/info_controller.rb b/railties/builtin/rails_info/rails/info_controller.rb index 05745d606d..47e87c5bf5 100644 --- a/railties/builtin/rails_info/rails/info_controller.rb +++ b/railties/builtin/rails_info/rails/info_controller.rb @@ -3,7 +3,7 @@ class Rails::InfoController < ActionController::Base if consider_all_requests_local || local_request? render :inline => Rails::Info.to_html else - render :text => '

For security purposes, this information is only available to local requests.

', :status => 500 + render :text => '

For security purposes, this information is only available to local requests.

', :status => :forbidden end end end diff --git a/railties/test/rails_info_controller_test.rb b/railties/test/rails_info_controller_test.rb index e274e1aa6e..607ece99a9 100644 --- a/railties/test/rails_info_controller_test.rb +++ b/railties/test/rails_info_controller_test.rb @@ -2,51 +2,45 @@ require 'abstract_unit' require 'action_controller' require 'action_controller/test_process' -module Rails; end require 'rails/info' require 'rails/info_controller' -class Rails::InfoController < ActionController::Base - @local_request = false - class << self - cattr_accessor :local_request - end - - # Re-raise errors caught by the controller. - def rescue_action(e) raise e end; - -protected - def local_request? - self.class.local_request - end -end - ActionController::Routing::Routes.draw do |map| map.connect ':controller/:action/:id' end -class Rails::InfoControllerTest < ActionController::TestCase +class InfoControllerTest < ActionController::TestCase + tests Rails::InfoController + def setup - @controller = Rails::InfoController.new - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new + @controller.stubs(:consider_all_requests_local => false, :local_request? => true) + end + + test "info controller does not allow remote requests" do + @controller.stubs(:consider_all_requests_local => false, :local_request? => false) + get :properties + assert_response :forbidden + end - ActionController::Base.consider_all_requests_local = true + test "info controller renders an error message when request was forbidden" do + @controller.stubs(:consider_all_requests_local => false, :local_request? => false) + get :properties + assert_select 'p' + end + + test "info controller allows requests when all requests are considered local" do + @controller.stubs(:consider_all_requests_local => true, :local_request? => false) + get :properties + assert_response :success end - def test_rails_info_properties_table_rendered_for_local_request - Rails::InfoController.local_request = true + test "info controller allows local requests" do get :properties - assert_tag :tag => 'table' assert_response :success end - - def test_rails_info_properties_error_rendered_for_non_local_request - Rails::InfoController.local_request = false - ActionController::Base.consider_all_requests_local = false + test "info controller renders a table with properties" do get :properties - assert_tag :tag => 'p' - assert_response 500 + assert_select 'table' end end diff --git a/railties/test/rails_info_test.rb b/railties/test/rails_info_test.rb index 9befd44a58..971cba89d0 100644 --- a/railties/test/rails_info_test.rb +++ b/railties/test/rails_info_test.rb @@ -1,9 +1,12 @@ $:.unshift File.dirname(__FILE__) + "/../lib" $:.unshift File.dirname(__FILE__) + "/../builtin/rails_info" $:.unshift File.dirname(__FILE__) + "/../../activesupport/lib" +$:.unshift File.dirname(__FILE__) + "/../../actionpack/lib" require 'test/unit' require 'active_support' +require 'active_support/test_case' +require 'action_controller' unless defined?(Rails) && defined?(Rails::Info) module Rails @@ -11,7 +14,7 @@ unless defined?(Rails) && defined?(Rails::Info) end end -class InfoTest < Test::Unit::TestCase +class InfoTest < ActiveSupport::TestCase def setup Rails.send :remove_const, :Info silence_warnings { load 'rails/info.rb' } @@ -72,6 +75,18 @@ EOS end end + def test_middleware_property + assert property_defined?('Middleware') + end + + def test_html_includes_middleware + html = Rails::Info.to_html + assert html.include?('Middleware') + properties.value_for('Middleware').each do |value| + assert html.include?("
  • #{CGI.escapeHTML(value)}
  • ") + end + end + protected def svn_info=(info) Rails::Info.module_eval do -- cgit v1.2.3 From d9afc51391e9a22759080399f973ab361d6d51af Mon Sep 17 00:00:00 2001 From: Carl Lerche & Yehuda Katz Date: Mon, 13 Apr 2009 17:16:07 -0700 Subject: Rails server boots again --- railties/guides/source/rails_on_rack.textile | 2 +- railties/lib/initializer.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'railties') diff --git a/railties/guides/source/rails_on_rack.textile b/railties/guides/source/rails_on_rack.textile index 05581f943f..1164ed821d 100644 --- a/railties/guides/source/rails_on_rack.textile +++ b/railties/guides/source/rails_on_rack.textile @@ -101,7 +101,7 @@ use Rack::Lock use ActionController::Failsafe use ActionController::Session::CookieStore, , {:secret=>"", :session_key=>"__session"} use Rails::Rack::Metal -use ActionController::RewindableInput +use ActionDispatch::RewindableInput use ActionController::ParamsParser use Rack::MethodOverride use Rack::Head diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb index 8eb4212737..c9716f508a 100644 --- a/railties/lib/initializer.rb +++ b/railties/lib/initializer.rb @@ -568,7 +568,7 @@ Run `rake gems:install` to install the missing gems. Rails::Rack::Metal.metal_paths += plugin_loader.engine_metal_paths configuration.middleware.insert_before( - :"ActionController::RewindableInput", + :"ActionDispatch::RewindableInput", Rails::Rack::Metal, :if => Rails::Rack::Metal.metals.any?) end -- cgit v1.2.3 From 1120aaceae95b95ef491ca226154500051b5fe38 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Tue, 14 Apr 2009 10:53:46 -0500 Subject: Fix requires so tests run --- railties/lib/test_help.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'railties') diff --git a/railties/lib/test_help.rb b/railties/lib/test_help.rb index ee24ea3a45..94e089a624 100644 --- a/railties/lib/test_help.rb +++ b/railties/lib/test_help.rb @@ -3,9 +3,9 @@ silence_warnings { RAILS_ENV = "test" } require 'test/unit' -require 'action_controller/test_case' +require 'action_controller/testing/test_case' require 'action_view/test_case' -require 'action_controller/integration' +require 'action_controller/testing/integration' require 'action_mailer/test_case' if defined?(ActionMailer) if defined?(ActiveRecord) -- cgit v1.2.3 From 3c1187699a80e0c4a003f5693389595cd644390f Mon Sep 17 00:00:00 2001 From: Carl Lerche & Yehuda Katz Date: Tue, 14 Apr 2009 17:22:51 -0700 Subject: Makes rails-dev-boost work again --- railties/lib/initializer.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties') diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb index c9716f508a..a03be59a2b 100644 --- a/railties/lib/initializer.rb +++ b/railties/lib/initializer.rb @@ -379,7 +379,7 @@ Run `rake gems:install` to install the missing gems. def load_view_paths if configuration.frameworks.include?(:action_view) if configuration.cache_classes - view_path = ActionView::Template::EagerPath.new(configuration.view_path) + view_path = ActionView::Template::FileSystemPath.new(configuration.view_path) ActionController::Base.view_paths = view_path if configuration.frameworks.include?(:action_controller) ActionMailer::Base.template_root = view_path if configuration.frameworks.include?(:action_mailer) end -- cgit v1.2.3 From 5b92dcb6757e90da316bd0c7a8472b9fa737f268 Mon Sep 17 00:00:00 2001 From: lifo Date: Fri, 17 Apr 2009 14:28:46 +0100 Subject: Merge docrails --- railties/guides/rails_guides/generator.rb | 2 +- railties/guides/rails_guides/levenshtein.rb | 48 +++++++-------- railties/guides/source/2_3_release_notes.textile | 2 +- .../guides/source/action_view_overview.textile | 69 ++++++++++++++++++++++ railties/guides/source/getting_started.textile | 2 +- .../source/rails_application_templates.textile | 18 ++++++ 6 files changed, 115 insertions(+), 26 deletions(-) create mode 100644 railties/guides/source/action_view_overview.textile create mode 100644 railties/guides/source/rails_application_templates.textile (limited to 'railties') diff --git a/railties/guides/rails_guides/generator.rb b/railties/guides/rails_guides/generator.rb index f93282db2e..2a4714b13a 100644 --- a/railties/guides/rails_guides/generator.rb +++ b/railties/guides/rails_guides/generator.rb @@ -48,7 +48,7 @@ module RailsGuides if guide =~ /\.erb\.textile/ # Generate the erb pages with textile formatting - e.g. index/authors - result = view.render(:layout => 'layout', :file => name) + result = view.render(:layout => 'layout', :file => guide) f.write textile(result) else body = File.read(File.join(view_path, guide)) diff --git a/railties/guides/rails_guides/levenshtein.rb b/railties/guides/rails_guides/levenshtein.rb index 4010b61e26..f99c6e6ba8 100644 --- a/railties/guides/rails_guides/levenshtein.rb +++ b/railties/guides/rails_guides/levenshtein.rb @@ -1,29 +1,31 @@ -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 +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 } + # 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 + # 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 - end - # all done - return d[m][n] + # all done + return d[m][n] + end end end diff --git a/railties/guides/source/2_3_release_notes.textile b/railties/guides/source/2_3_release_notes.textile index 6a97fd2cd1..bb2998fbdf 100644 --- a/railties/guides/source/2_3_release_notes.textile +++ b/railties/guides/source/2_3_release_notes.textile @@ -582,7 +582,7 @@ h4. Other Railties Changes * 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-dispatches+ when you run the +rails+ command, or add them later with +rake rails:generate_dispatchers+). +* 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 --path argument to mount a Rails application from a specific path. diff --git a/railties/guides/source/action_view_overview.textile b/railties/guides/source/action_view_overview.textile new file mode 100644 index 0000000000..ebc267ab71 --- /dev/null +++ b/railties/guides/source/action_view_overview.textile @@ -0,0 +1,69 @@ +h2. Action View Overview + +In this guide you will learn: + +* What Action View is, and how to use it + +endprologue. + +h3. What is Action View? + +TODO... + +h3. Using Action View with Rails + +TODO... + +h3. Using Action View outside of Rails + +TODO... + +h3. Templates, Partials and Layouts + +TODO... + +h3. Using Templates, Partials and Layouts in "The Rails Way" + +TODO... + +h3. Partial Layouts + +TODO... + +h3. View Paths + +TODO... + +h3. Overview of all the helpers provided by AV + +TODO... + +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. + +TODO add full code example... + +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+: + + +before_filter :set_expert_locale + +def set_expert_locale + I18n.locale = :expert if current_user.expert? +end + + +Then you could create special views like +app/views/posts/show.expert.html.erb+, which would only be displayed to expert users. + +You can read more about the Rails Internationalization (I18n) API "here":i18n.html. + +h3. Changelog + +"Lighthouse Ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/71 + +* April 5, 2009: Starting work by Trevor Turk, leveraging Mike Gunderloy's docs diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile index a216201490..7c029762a3 100644 --- a/railties/guides/source/getting_started.textile +++ b/railties/guides/source/getting_started.textile @@ -1269,7 +1269,7 @@ You'll also need to modify +views/posts/_form.html.erb+ to include the tags: With these changes in place, you'll find that you can edit a post and its tags directly on the same view. -NOTE. You may want to use javascript to dynamically add additional tags on a single form. For an example of this and other advanced techniques, see the "nested model sample application":http://github.com/alloy/complex-form-examples/tree/nested_attributes. +NOTE. You may want to use JavaScript to dynamically add additional tags on a single form. For an example of this and other advanced techniques, see the "complex form examples application":http://github.com/alloy/complex-form-examples/tree/master. h3. What's Next? diff --git a/railties/guides/source/rails_application_templates.textile b/railties/guides/source/rails_application_templates.textile new file mode 100644 index 0000000000..49cd5bf5f5 --- /dev/null +++ b/railties/guides/source/rails_application_templates.textile @@ -0,0 +1,18 @@ +h2. Rails Application Templates + +This guide covers the Rails application templates, By referring to this guide, you will be able to: + +* Use existing templates to generate a customized Rails application +* Write your own reusable Rails application templates + +endprologue. + +h3. Introduction + +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. + +h3. Changelog + +"Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/78 + +* April 17, 2009: Initial version by "Pratik":credits.html#lifo -- cgit v1.2.3