actionpack 0.9.0

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of actionpack might be problematic. Click here for more details.

Files changed (100) hide show
  1. data/CHANGELOG +604 -0
  2. data/MIT-LICENSE +21 -0
  3. data/README +418 -0
  4. data/RUNNING_UNIT_TESTS +14 -0
  5. data/examples/.htaccess +24 -0
  6. data/examples/address_book/index.rhtml +33 -0
  7. data/examples/address_book/layout.rhtml +8 -0
  8. data/examples/address_book_controller.cgi +9 -0
  9. data/examples/address_book_controller.fcgi +6 -0
  10. data/examples/address_book_controller.rb +52 -0
  11. data/examples/address_book_controller.rbx +4 -0
  12. data/examples/benchmark.rb +52 -0
  13. data/examples/benchmark_with_ar.fcgi +89 -0
  14. data/examples/blog_controller.cgi +53 -0
  15. data/examples/debate/index.rhtml +14 -0
  16. data/examples/debate/new_topic.rhtml +22 -0
  17. data/examples/debate/topic.rhtml +32 -0
  18. data/examples/debate_controller.cgi +57 -0
  19. data/install.rb +93 -0
  20. data/lib/action_controller.rb +47 -0
  21. data/lib/action_controller/assertions/action_pack_assertions.rb +166 -0
  22. data/lib/action_controller/assertions/active_record_assertions.rb +65 -0
  23. data/lib/action_controller/base.rb +626 -0
  24. data/lib/action_controller/benchmarking.rb +49 -0
  25. data/lib/action_controller/cgi_ext/cgi_ext.rb +43 -0
  26. data/lib/action_controller/cgi_ext/cgi_methods.rb +91 -0
  27. data/lib/action_controller/cgi_process.rb +123 -0
  28. data/lib/action_controller/filters.rb +279 -0
  29. data/lib/action_controller/flash.rb +65 -0
  30. data/lib/action_controller/layout.rb +143 -0
  31. data/lib/action_controller/request.rb +92 -0
  32. data/lib/action_controller/rescue.rb +94 -0
  33. data/lib/action_controller/response.rb +15 -0
  34. data/lib/action_controller/scaffolding.rb +183 -0
  35. data/lib/action_controller/session/active_record_store.rb +72 -0
  36. data/lib/action_controller/session/drb_server.rb +9 -0
  37. data/lib/action_controller/session/drb_store.rb +31 -0
  38. data/lib/action_controller/support/class_attribute_accessors.rb +57 -0
  39. data/lib/action_controller/support/class_inheritable_attributes.rb +37 -0
  40. data/lib/action_controller/support/clean_logger.rb +10 -0
  41. data/lib/action_controller/support/cookie_performance_fix.rb +121 -0
  42. data/lib/action_controller/support/inflector.rb +70 -0
  43. data/lib/action_controller/templates/rescues/_request_and_response.rhtml +28 -0
  44. data/lib/action_controller/templates/rescues/diagnostics.rhtml +22 -0
  45. data/lib/action_controller/templates/rescues/layout.rhtml +29 -0
  46. data/lib/action_controller/templates/rescues/missing_template.rhtml +2 -0
  47. data/lib/action_controller/templates/rescues/template_error.rhtml +26 -0
  48. data/lib/action_controller/templates/rescues/unknown_action.rhtml +2 -0
  49. data/lib/action_controller/templates/scaffolds/edit.rhtml +6 -0
  50. data/lib/action_controller/templates/scaffolds/layout.rhtml +29 -0
  51. data/lib/action_controller/templates/scaffolds/list.rhtml +24 -0
  52. data/lib/action_controller/templates/scaffolds/new.rhtml +5 -0
  53. data/lib/action_controller/templates/scaffolds/show.rhtml +9 -0
  54. data/lib/action_controller/test_process.rb +194 -0
  55. data/lib/action_controller/url_rewriter.rb +153 -0
  56. data/lib/action_view.rb +40 -0
  57. data/lib/action_view/base.rb +253 -0
  58. data/lib/action_view/helpers/active_record_helper.rb +171 -0
  59. data/lib/action_view/helpers/date_helper.rb +223 -0
  60. data/lib/action_view/helpers/debug_helper.rb +17 -0
  61. data/lib/action_view/helpers/form_helper.rb +176 -0
  62. data/lib/action_view/helpers/form_options_helper.rb +169 -0
  63. data/lib/action_view/helpers/tag_helper.rb +59 -0
  64. data/lib/action_view/helpers/text_helper.rb +129 -0
  65. data/lib/action_view/helpers/url_helper.rb +72 -0
  66. data/lib/action_view/partials.rb +61 -0
  67. data/lib/action_view/template_error.rb +84 -0
  68. data/lib/action_view/vendor/builder.rb +13 -0
  69. data/lib/action_view/vendor/builder/blankslate.rb +21 -0
  70. data/lib/action_view/vendor/builder/xmlbase.rb +143 -0
  71. data/lib/action_view/vendor/builder/xmlevents.rb +63 -0
  72. data/lib/action_view/vendor/builder/xmlmarkup.rb +288 -0
  73. data/rakefile +105 -0
  74. data/test/abstract_unit.rb +9 -0
  75. data/test/controller/action_pack_assertions_test.rb +295 -0
  76. data/test/controller/active_record_assertions_test.rb +118 -0
  77. data/test/controller/cgi_test.rb +142 -0
  78. data/test/controller/cookie_test.rb +38 -0
  79. data/test/controller/filters_test.rb +159 -0
  80. data/test/controller/flash_test.rb +69 -0
  81. data/test/controller/layout_test.rb +49 -0
  82. data/test/controller/redirect_test.rb +44 -0
  83. data/test/controller/render_test.rb +169 -0
  84. data/test/controller/url_test.rb +318 -0
  85. data/test/fixtures/layouts/builder.rxml +3 -0
  86. data/test/fixtures/layouts/standard.rhtml +1 -0
  87. data/test/fixtures/test/_customer.rhtml +1 -0
  88. data/test/fixtures/test/greeting.rhtml +1 -0
  89. data/test/fixtures/test/hello.rxml +4 -0
  90. data/test/fixtures/test/hello_world.rhtml +1 -0
  91. data/test/fixtures/test/hello_xml_world.rxml +11 -0
  92. data/test/fixtures/test/list.rhtml +1 -0
  93. data/test/template/active_record_helper_test.rb +76 -0
  94. data/test/template/date_helper_test.rb +103 -0
  95. data/test/template/form_helper_test.rb +115 -0
  96. data/test/template/form_options_helper_test.rb +174 -0
  97. data/test/template/tag_helper_test.rb +18 -0
  98. data/test/template/text_helper_test.rb +62 -0
  99. data/test/template/url_helper_test.rb +35 -0
  100. metadata +154 -0
@@ -0,0 +1,93 @@
1
+ require 'rbconfig'
2
+ require 'find'
3
+ require 'ftools'
4
+
5
+ include Config
6
+
7
+ # this was adapted from rdoc's install.rb by ways of Log4r
8
+
9
+ $sitedir = CONFIG["sitelibdir"]
10
+ unless $sitedir
11
+ version = CONFIG["MAJOR"] + "." + CONFIG["MINOR"]
12
+ $libdir = File.join(CONFIG["libdir"], "ruby", version)
13
+ $sitedir = $:.find {|x| x =~ /site_ruby/ }
14
+ if !$sitedir
15
+ $sitedir = File.join($libdir, "site_ruby")
16
+ elsif $sitedir !~ Regexp.quote(version)
17
+ $sitedir = File.join($sitedir, version)
18
+ end
19
+ end
20
+
21
+ makedirs = %w{ action_controller/cgi_ext action_controller/session
22
+ action_controller/support action_controller/templates
23
+ action_controller/templates/rescues action_controller/templates/scaffolds
24
+ action_view/helpers action_view/vendor action_view/vendor/builder
25
+ }
26
+
27
+
28
+ makedirs.each {|f| File::makedirs(File.join($sitedir, *f.split(/\//)))}
29
+
30
+ # deprecated files that should be removed
31
+ # deprecated = %w{ }
32
+
33
+ # files to install in library path
34
+ files = %w-
35
+ action_controller.rb
36
+ action_controller/base.rb
37
+ action_controller/benchmarking.rb
38
+ action_controller/cgi_ext/cgi_ext.rb
39
+ action_controller/cgi_ext/cgi_methods.rb
40
+ action_controller/cgi_process.rb
41
+ action_controller/filters.rb
42
+ action_controller/flash.rb
43
+ action_controller/layout.rb
44
+ action_controller/request.rb
45
+ action_controller/rescue.rb
46
+ action_controller/response.rb
47
+ action_controller/scaffolding.rb
48
+ action_controller/session/active_record_store.rb
49
+ action_controller/session/drb_server.rb
50
+ action_controller/session/drb_store.rb
51
+ action_controller/support/class_inheritable_attributes.rb
52
+ action_controller/support/class_attribute_accessors.rb
53
+ action_controller/support/clean_logger.rb
54
+ action_controller/support/cookie_performance_fix.rb
55
+ action_controller/support/inflector.rb
56
+ action_controller/templates/rescues/_request_and_response.rhtml
57
+ action_controller/templates/rescues/diagnostics.rhtml
58
+ action_controller/templates/rescues/layout.rhtml
59
+ action_controller/templates/rescues/missing_template.rhtml
60
+ action_controller/templates/rescues/template_error.rhtml
61
+ action_controller/templates/rescues/unknown_action.rhtml
62
+ action_controller/templates/scaffolds/edit.rhtml
63
+ action_controller/templates/scaffolds/layout.rhtml
64
+ action_controller/templates/scaffolds/list.rhtml
65
+ action_controller/templates/scaffolds/new.rhtml
66
+ action_controller/templates/scaffolds/show.rhtml
67
+ action_controller/test_process.rb
68
+ action_controller/url_rewriter.rb
69
+ action_view.rb
70
+ action_view/base.rb
71
+ action_view/helpers/active_record_helper.rb
72
+ action_view/helpers/date_helper.rb
73
+ action_view/helpers/debug_helper.rb
74
+ action_view/helpers/form_helper.rb
75
+ action_view/helpers/form_options_helper.rb
76
+ action_view/helpers/text_helper.rb
77
+ action_view/helpers/tag_helper.rb
78
+ action_view/helpers/url_helper.rb
79
+ action_view/partials.rb
80
+ action_view/template_error.rb
81
+ action_view/vendor/builder.rb
82
+ action_view/vendor/builder/blankslate.rb
83
+ action_view/vendor/builder/xmlbase.rb
84
+ action_view/vendor/builder/xmlevents.rb
85
+ action_view/vendor/builder/xmlmarkup.rb
86
+ -
87
+
88
+ # the acual gruntwork
89
+ Dir.chdir("lib")
90
+ # File::safe_unlink *deprecated.collect{|f| File.join($sitedir, f.split(/\//))}
91
+ files.each {|f|
92
+ File::install(f, File.join($sitedir, *f.split(/\//)), 0644, true)
93
+ }
@@ -0,0 +1,47 @@
1
+ #--
2
+ # Copyright (c) 2004 David Heinemeier Hansson
3
+ #
4
+ # Permission is hereby granted, free of charge, to any person obtaining
5
+ # a copy of this software and associated documentation files (the
6
+ # "Software"), to deal in the Software without restriction, including
7
+ # without limitation the rights to use, copy, modify, merge, publish,
8
+ # distribute, sublicense, and/or sell copies of the Software, and to
9
+ # permit persons to whom the Software is furnished to do so, subject to
10
+ # the following conditions:
11
+ #
12
+ # The above copyright notice and this permission notice shall be
13
+ # included in all copies or substantial portions of the Software.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
+ #++
23
+
24
+ $:.unshift(File.dirname(__FILE__))
25
+
26
+ require 'action_controller/support/clean_logger'
27
+
28
+ require 'action_controller/base'
29
+ require 'action_controller/rescue'
30
+ require 'action_controller/benchmarking'
31
+ require 'action_controller/filters'
32
+ require 'action_controller/layout'
33
+ require 'action_controller/flash'
34
+ require 'action_controller/scaffolding'
35
+ require 'action_controller/cgi_process'
36
+
37
+ ActionController::Base.class_eval do
38
+ include ActionController::Filters
39
+ include ActionController::Layout
40
+ include ActionController::Flash
41
+ include ActionController::Benchmarking
42
+ include ActionController::Rescue
43
+ include ActionController::Scaffolding
44
+ end
45
+
46
+ require 'action_view'
47
+ ActionController::Base.template_class = ActionView::Base
@@ -0,0 +1,166 @@
1
+ require 'test/unit'
2
+ require 'test/unit/assertions'
3
+ require 'rexml/document'
4
+
5
+ module Test #:nodoc:
6
+ module Unit #:nodoc:
7
+ # Adds a wealth of assertions to do functional testing of Action Controllers.
8
+ module Assertions
9
+ # -- basic assertions ---------------------------------------------------
10
+
11
+ # ensure that the web request has been serviced correctly
12
+ def assert_success(message=nil)
13
+ response = acquire_assertion_target
14
+ msg = build_message(message, "unsuccessful request (response code = <?>)", response.response_code)
15
+ assert_block(msg) { response.success? }
16
+ end
17
+
18
+ # ensure the request was rendered with the appropriate template file
19
+ def assert_rendered_file(expected=nil, message=nil)
20
+ response = acquire_assertion_target
21
+ msg = build_message(message, "expecting <?> but rendering with <?>", expected, response.rendered_file)
22
+ assert_block(msg) do
23
+ if expected.nil?
24
+ response.rendered_with_file?
25
+ else
26
+ expected != response.rendered_file(expected.include?('/'))
27
+ end
28
+ end
29
+ end
30
+
31
+ # -- session assertions -------------------------------------------------
32
+
33
+ # ensure that the session has an object with the specified name
34
+ def assert_session_has(key=nil, message=nil)
35
+ response = acquire_assertion_target
36
+ msg = build_message(message, "<?> is not in the session <?>", key, response.session)
37
+ assert_block(msg) { response.has_session_object?(key) }
38
+ end
39
+
40
+ # ensure that the session has no object with the specified name
41
+ def assert_session_has_no(key=nil, message=nil)
42
+ response = acquire_assertion_target
43
+ msg = build_message(message, "<?> is in the session <?>", key, response.session)
44
+ assert_block(msg) { !response.has_session_object?(key) }
45
+ end
46
+
47
+ # -- flash assertions ---------------------------------------------------
48
+
49
+ # ensure that the flash has an object with the specified name
50
+ def assert_flash_has(key=nil, message=nil)
51
+ response = acquire_assertion_target
52
+ msg = build_message(message, "<?> is not in the flash <?>", key, response.flash)
53
+ assert_block(msg) { response.has_flash_object?(key) }
54
+ end
55
+
56
+ # ensure that the flash has no object with the specified name
57
+ def assert_flash_has_no(key=nil, message=nil)
58
+ response = acquire_assertion_target
59
+ msg = build_message(message, "<?> is in the flash <?>", key, response.flash)
60
+ assert_block(msg) { !response.has_flash_object?(key) }
61
+ end
62
+
63
+ # ensure the flash exists
64
+ def assert_flash_exists(message=nil)
65
+ response = acquire_assertion_target
66
+ msg = build_message(message, "the flash does not exist <?>", response.session['flash'] )
67
+ assert_block(msg) { response.has_flash? }
68
+ end
69
+
70
+ # ensure the flash does not exist
71
+ def assert_flash_not_exists(message=nil)
72
+ response = acquire_assertion_target
73
+ msg = build_message(message, "the flash exists <?>", response.flash)
74
+ assert_block(msg) { !response.has_flash? }
75
+ end
76
+
77
+ # ensure the flash is empty but existant
78
+ def assert_flash_empty(message=nil)
79
+ response = acquire_assertion_target
80
+ msg = build_message(message, "the flash is not empty <?>", response.flash)
81
+ assert_block(msg) { !response.has_flash_with_contents? }
82
+ end
83
+
84
+ # ensure the flash is not empty
85
+ def assert_flash_not_empty(message=nil)
86
+ response = acquire_assertion_target
87
+ msg = build_message(message, "the flash is empty")
88
+ assert_block(msg) { response.has_flash_with_contents? }
89
+ end
90
+
91
+ # -- redirection assertions ---------------------------------------------
92
+
93
+ # ensure we have be redirected
94
+ def assert_redirect(message=nil)
95
+ response = acquire_assertion_target
96
+ msg = build_message(message, "response is not a redirection (response code is <?>)", response.response_code)
97
+ assert_block(msg) { response.redirect? }
98
+ end
99
+
100
+ def assert_redirected_to(options = {}, message=nil)
101
+ assert_redirect(message)
102
+ response = acquire_assertion_target
103
+
104
+ msg = build_message(message, "response is not a redirection to all of the options supplied (redirection is <?>)", response.redirected_to)
105
+ assert_block(msg) do
106
+ response.redirected_to == options ||
107
+ options.keys.all? { |k| options[k] == response.redirected_to[k] }
108
+ end
109
+ end
110
+
111
+ # ensure our redirection url is an exact match
112
+ def assert_redirect_url(url=nil, message=nil)
113
+ assert_redirect(message)
114
+ response = acquire_assertion_target
115
+ msg = build_message(message, "<?> is not the redirected location <?>", url, response.redirect_url)
116
+ assert_block(msg) { response.redirect_url == url }
117
+ end
118
+
119
+ # ensure our redirection url matches a pattern
120
+ def assert_redirect_url_match(pattern=nil, message=nil)
121
+ assert_redirect(message)
122
+ response = acquire_assertion_target
123
+ msg = build_message(message, "<?> was not found in the location: <?>", pattern, response.redirect_url)
124
+ assert_block(msg) { response.redirect_url_match?(pattern) }
125
+ end
126
+
127
+ # -- template assertions ------------------------------------------------
128
+
129
+ # ensure that a template object with the given name exists
130
+ def assert_template_has(key=nil, message=nil)
131
+ response = acquire_assertion_target
132
+ msg = build_message(message, "<?> is not a template object", key )
133
+ assert_block(msg) { response.has_template_object?(key) }
134
+ end
135
+
136
+ # ensure that a template object with the given name does not exist
137
+ def assert_template_has_no(key=nil,message=nil)
138
+ response = acquire_assertion_target
139
+ msg = build_message(message, "<?> is a template object <?>", key, response.template_objects[key])
140
+ assert_block(msg) { !response.has_template_object?(key) }
141
+ end
142
+
143
+ # Asserts that the template returns the +expected+ string or array based on the XPath +expression+.
144
+ # This will only work if the template rendered a valid XML document.
145
+ def assert_template_xpath_match(expression=nil, expected=nil, message=nil)
146
+ response = acquire_assertion_target
147
+ xml, matches = REXML::Document.new(response.body), []
148
+ xml.elements.each(expression) { |e| matches << e.text }
149
+ matches = matches.first if matches.length < 2
150
+
151
+ msg = build_message(message, "<?> found <?>, not <?>", expression, matches, expected)
152
+ assert_block(msg) { matches == expected }
153
+ end
154
+
155
+ # -- helper functions ---------------------------------------------------
156
+
157
+ # get the TestResponse object that these assertions depend upon
158
+ def acquire_assertion_target
159
+ target = ActionController::TestResponse.assertion_target
160
+ assert_block( "Unable to acquire the TestResponse.assertion_target. Please set this before calling this assertion." ) { !target.nil? }
161
+ target
162
+ end
163
+
164
+ end # Assertions
165
+ end # Unit
166
+ end # Test
@@ -0,0 +1,65 @@
1
+ require 'test/unit'
2
+ require 'test/unit/assertions'
3
+ # active_record is assumed to be loaded by this point
4
+
5
+ module Test #:nodoc:
6
+ module Unit #:nodoc:
7
+ module Assertions
8
+ # Assert the template object with the given name is an Active Record descendant and is valid.
9
+ def assert_valid_record(key = nil, message = nil)
10
+ record = find_record_in_template(key)
11
+ msg = build_message(message, "Active Record is invalid <?>)", record.errors.full_messages)
12
+ assert_block(msg) { record.valid? }
13
+ end
14
+
15
+ # Assert the template object with the given name is an Active Record descendant and is invalid.
16
+ def assert_invalid_record(key = nil, message = nil)
17
+ record = find_record_in_template(key)
18
+ msg = build_message(message, "Active Record is valid)")
19
+ assert_block(msg) { !record.valid? }
20
+ end
21
+
22
+ # Assert the template object with the given name is an Active Record descendant and the specified column(s) are valid.
23
+ def assert_valid_column_on_record(key = nil, columns = "", message = nil)
24
+ record = find_record_in_template(key)
25
+ record.validate
26
+
27
+ cols = glue_columns(columns)
28
+ cols.delete_if { |col| !record.errors.invalid?(col) }
29
+ msg = build_message(message, "Active Record has invalid columns <?>)", cols.join(",") )
30
+ assert_block(msg) { cols.empty? }
31
+ end
32
+
33
+ # Assert the template object with the given name is an Active Record descendant and the specified column(s) are invalid.
34
+ def assert_invalid_column_on_record(key = nil, columns = "", message = nil)
35
+ record = find_record_in_template(key)
36
+ record.validate
37
+
38
+ cols = glue_columns(columns)
39
+ cols.delete_if { |col| record.errors.invalid?(col) }
40
+ msg = build_message(message, "Active Record has valid columns <?>)", cols.join(",") )
41
+ assert_block(msg) { cols.empty? }
42
+ end
43
+
44
+ private
45
+ def glue_columns(columns)
46
+ cols = []
47
+ cols << columns if columns.class == String
48
+ cols += columns if columns.class == Array
49
+ cols
50
+ end
51
+
52
+ def find_record_in_template(key = nil)
53
+ response = acquire_assertion_target
54
+
55
+ assert_template_has(key)
56
+ record = response.template_objects[key]
57
+
58
+ assert_not_nil(record)
59
+ assert_kind_of ActiveRecord::Base, record
60
+
61
+ return record
62
+ end
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,626 @@
1
+ require 'action_controller/request'
2
+ require 'action_controller/response'
3
+ require 'action_controller/url_rewriter'
4
+ require 'action_controller/support/class_attribute_accessors'
5
+ require 'action_controller/support/class_inheritable_attributes'
6
+ require 'action_controller/support/inflector'
7
+
8
+ module ActionController #:nodoc:
9
+ class ActionControllerError < StandardError #:nodoc:
10
+ end
11
+ class SessionRestoreError < ActionControllerError #:nodoc:
12
+ end
13
+ class MissingTemplate < ActionControllerError #:nodoc:
14
+ end
15
+ class UnknownAction < ActionControllerError #:nodoc:
16
+ end
17
+
18
+ # Action Controllers are made up of one or more actions that performs its purpose and then either renders a template or
19
+ # redirects to another action. An action is defined as a public method on the controller, which will automatically be
20
+ # made accessible to the web-server through a mod_rewrite mapping. A sample controller could look like this:
21
+ #
22
+ # class GuestBookController < ActionController::Base
23
+ # def index
24
+ # @entries = Entry.find_all
25
+ # end
26
+ #
27
+ # def sign
28
+ # Entry.create(@params["entry"])
29
+ # redirect_to :action => "index"
30
+ # end
31
+ # end
32
+ #
33
+ # GuestBookController.template_root = "templates/"
34
+ # GuestBookController.process_cgi
35
+ #
36
+ # All actions assume that you want to render a template matching the name of the action at the end of the performance
37
+ # unless you tell it otherwise. The index action complies with this assumption, so after populating the @entries instance
38
+ # variable, the GuestBookController will render "templates/guestbook/index.rhtml".
39
+ #
40
+ # Unlike index, the sign action isn't interested in rendering a template. So after performing its main purpose (creating a
41
+ # new entry in the guest book), it sheds the rendering assumption and initiates a redirect instead. This redirect works by
42
+ # returning an external "302 Moved" HTTP response that takes the user to the index action.
43
+ #
44
+ # The index and sign represent the two basic action archetypes used in Action Controllers. Get-and-show and do-and-redirect.
45
+ # Most actions are variations of these themes.
46
+ #
47
+ # Also note that it's the final call to <tt>process_cgi</tt> that actually initiates the action performance. It will extract
48
+ # request and response objects from the CGI
49
+ #
50
+ # == Requests
51
+ #
52
+ # Requests are processed by the Action Controller framework by extracting the value of the "action" key in the request parameters.
53
+ # This value should hold the name of the action to be performed. Once the action has been identified, the remaining
54
+ # request parameters, the session (if one is available), and the full request with all the http headers are made available to
55
+ # the action through instance variables. Then the action is performed.
56
+ #
57
+ # The full request object is available in @request and is primarily used to query for http headers. These queries are made by
58
+ # accessing the environment hash, like this:
59
+ #
60
+ # def hello_ip
61
+ # location = @request.env["REMOTE_ADDRESS"]
62
+ # render_text "Hello stranger from #{location}"
63
+ # end
64
+ #
65
+ # == Parameters
66
+ #
67
+ # All request parameters whether they come from a GET or POST request, or from the URL, are available through the @params hash.
68
+ # So an action that was performed through /weblog/list?category=All&limit=5 will include { "category" => "All", "limit" => 5 }
69
+ # in @params.
70
+ #
71
+ # It's also possible to construct multi-dimensional parameter hashes by specifying keys using brackets, such as:
72
+ #
73
+ # <input type="text" name="post[name]" value="david">
74
+ # <input type="text" name="post[address]" value="hyacintvej">
75
+ #
76
+ # A request stemming from a form holding these inputs will include { "post" # => { "name" => "david", "address" => "hyacintvej" } }.
77
+ # If the address input had been named "post[address][street]", the @params would have included
78
+ # { "post" => { "address" => { "street" => "hyacintvej" } } }. There's no limit to the depth of the nesting.
79
+ #
80
+ # == Sessions
81
+ #
82
+ # Sessions allows you to store objects in memory between requests. This is useful for objects that are not yet ready to be persisted,
83
+ # such as a Signup object constructed in a multi-paged process, or objects that don't change much and are needed all the time, such
84
+ # as a User object for a system that requires login. The session should not be used, however, as a cache for objects where it's likely
85
+ # they could be changed unknowingly. It's usually too much work to keep it all synchronized -- something databases already excel at.
86
+ #
87
+ # You can place objects in the session by using the <tt>@session</tt> hash:
88
+ #
89
+ # @session["person"] = Person.authenticate(user_name, password)
90
+ #
91
+ # And retrieved again through the same hash:
92
+ #
93
+ # Hello #{@session["person"]}
94
+ #
95
+ # Any object can be placed in the session (as long as it can be Marshalled). But remember that 1000 active sessions each storing a
96
+ # 50kb object could lead to a 50MB memory overhead. In other words, think carefully about size and caching before resorting to the use
97
+ # of the session.
98
+ #
99
+ # == Responses
100
+ #
101
+ # Each action results in a response, which holds the headers and document to be sent to the user's browser. The actual response
102
+ # object is generated automatically through the use of renders and redirects, so it's normally nothing you'll need to be concerned about.
103
+ #
104
+ # == Renders
105
+ #
106
+ # Action Controller sends content to the user by using one of five rendering methods. The most versatile and common is the rendering
107
+ # of a template. Included in the Action Pack is the Action View, which enables rendering of ERb templates. It's automatically configured.
108
+ # The controller passes objects to the view by assigning instance variables:
109
+ #
110
+ # def show
111
+ # @post = Post.find(@params["id"])
112
+ # end
113
+ #
114
+ # Which are then automatically available to the view:
115
+ #
116
+ # Title: <%= @post.title %>
117
+ #
118
+ # You don't have to rely on the automated rendering. Especially actions that could result in the rendering of different templates will use
119
+ # the manual rendering methods:
120
+ #
121
+ # def search
122
+ # @results = Search.find(@params["query"])
123
+ # case @results
124
+ # when 0 then render "weblog/no_results"
125
+ # when 1 then render_action "show"
126
+ # when 2..10 then render_action "show_many"
127
+ # end
128
+ # end
129
+ #
130
+ # Read more about writing ERb and Builder templates in link:classes/ActionView/Base.html.
131
+ #
132
+ # == Redirects
133
+ #
134
+ # Redirecting is what actions that update the model do when they're done. The <tt>save_post</tt> method shouldn't be responsible for also
135
+ # showing the post once it's saved -- that's the job for <tt>show_post</tt>. So once <tt>save_post</tt> has completed its business, it'll
136
+ # redirect to <tt>show_post</tt>. All redirects are external, which means that when the user refreshes his browser, it's not going to save
137
+ # the post again, but rather just show it one more time.
138
+ #
139
+ # This sounds fairly simple, but the redirection is complicated by the quest for a phenomenon known as "pretty urls". Instead of accepting
140
+ # the dreadful beings that is "weblog_controller?action=show&post_id=5", Action Controller goes out of its way to represent the former as
141
+ # "/weblog/show/5". And this is even the simple case. As an example of a more advanced pretty url consider
142
+ # "/library/books/ISBN/0743536703/show", which can be mapped to books_controller?action=show&type=ISBN&id=0743536703.
143
+ #
144
+ # Redirects work by rewriting the URL of the current action. So if the show action was called by "/library/books/ISBN/0743536703/show",
145
+ # we can redirect to an edit action simply by doing <tt>redirect_to(:action => "edit")</tt>, which could throw the user to
146
+ # "/library/books/ISBN/0743536703/edit". Naturally, you'll need to setup the .htaccess (or other means of URL rewriting for the web server)
147
+ # to point to the proper controller and action in the first place, but once you have, it can be rewritten with ease.
148
+ #
149
+ # Let's consider a bunch of examples on how to go from "/library/books/ISBN/0743536703/edit" to somewhere else:
150
+ #
151
+ # redirect_to(:action => "show", :action_prefix => "XTC/123") =>
152
+ # "http://www.singlefile.com/library/books/XTC/123/show"
153
+ #
154
+ # redirect_to(:path_params => {"type" => "EXBC"}) =>
155
+ # "http://www.singlefile.com/library/books/EXBC/0743536703/show"
156
+ #
157
+ # redirect_to(:controller => "settings") =>
158
+ # "http://www.singlefile.com/library/settings/"
159
+ #
160
+ # For more examples of redirecting options, have a look at the unit test in test/controller/url_test.rb. It's very readable and will give
161
+ # you an excellent understanding of the different options and what they do.
162
+ #
163
+ # == Environments
164
+ #
165
+ # Action Controller works out of the box with CGI, FastCGI, and mod_ruby. CGI and mod_ruby controllers are triggered just the same using:
166
+ #
167
+ # WeblogController.process_cgi
168
+ #
169
+ # FastCGI controllers are triggered using:
170
+ #
171
+ # FCGI.each_cgi{ |cgi| WeblogController.process_cgi(cgi) }
172
+ class Base
173
+ include ClassInheritableAttributes
174
+
175
+ DEFAULT_RENDER_STATUS_CODE = "200 OK"
176
+
177
+ # Determines whether the view has access to controller internals @request, @response, @session, and @template.
178
+ # By default, it does.
179
+ @@view_controller_internals = true
180
+ cattr_accessor :view_controller_internals
181
+
182
+ # All requests are considered local by default, so everyone will be exposed to detailed debugging screens on errors.
183
+ # When the application is ready to go public, this should be set to false, and the protected method <tt>local_request?</tt>
184
+ # should instead be implemented in the controller to determine when debugging screens should be shown.
185
+ @@consider_all_requests_local = true
186
+ cattr_accessor :consider_all_requests_local
187
+
188
+ # Template root determines the base from which template references will be made. So a call to render("test/template")
189
+ # will be converted to "#{template_root}/test/template.rhtml".
190
+ cattr_accessor :template_root
191
+
192
+ # The logger is used for generating information on the action run-time (including benchmarking) if available.
193
+ # Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.
194
+ cattr_accessor :logger
195
+
196
+ # Determines which template class should be used by ActionController.
197
+ cattr_accessor :template_class
198
+
199
+ # Turn on +ignore_missing_templates+ if you want to unit test actions without making the associated templates.
200
+ cattr_accessor :ignore_missing_templates
201
+
202
+ # Holds the request object that's primarily used to get environment variables through access like
203
+ # <tt>@request.env["REQUEST_URI"]</tt>.
204
+ attr_accessor :request
205
+
206
+ # Holds a hash of all the GET, POST, and Url parameters passed to the action. Accessed like <tt>@params["post_id"]</tt>
207
+ # to get the post_id. No type casts are made, so all values are returned as strings.
208
+ attr_accessor :params
209
+
210
+ # Holds the response object that's primarily used to set additional HTTP headers through access like
211
+ # <tt>@response.headers["Cache-Control"] = "no-cache"</tt>. Can also be used to access the final body HTML after a template
212
+ # has been rendered through @response.body -- useful for <tt>after_filter</tt>s that wants to manipulate the output,
213
+ # such as a OutputCompressionFilter.
214
+ attr_accessor :response
215
+
216
+ # Holds a hash of objects in the session. Accessed like <tt>@session["person"]</tt> to get the object tied to the "person"
217
+ # key. The session will hold any type of object as values, but the key should be a string.
218
+ attr_accessor :session
219
+
220
+ # Holds a hash of header names and values. Accessed like <tt>@headers["Cache-Control"]</tt> to get the value of the Cache-Control
221
+ # directive. Values should always be specified as strings.
222
+ attr_accessor :headers
223
+
224
+ # Holds a hash of cookie names and values. Accessed like <tt>@cookies["user_name"]</tt> to get the value of the user_name cookie.
225
+ # This hash is read-only. You set new cookies using the cookie method.
226
+ attr_accessor :cookies
227
+
228
+ # Holds the hash of variables that are passed on to the template class to be made available to the view. This hash
229
+ # is generated by taking a snapshot of all the instance variables in the current scope just before a template is rendered.
230
+ attr_accessor :assigns
231
+
232
+ class << self
233
+ # Factory for the standard create, process loop where the controller is discarded after processing.
234
+ def process(request, response) #:nodoc:
235
+ new.process(request, response)
236
+ end
237
+
238
+ # Makes all the (instance) methods in the helper module available to templates rendered through this controller.
239
+ # See ActionView::Helpers (link:classes/ActionView/Helpers.html) for more about making your own helper modules
240
+ # available to the templates.
241
+ def add_template_helper(helper_module)
242
+ template_class.class_eval "include #{helper_module}"
243
+ end
244
+ end
245
+
246
+ public
247
+ # Extracts the action_name from the request parameters and performs that action.
248
+ def process(request, response) #:nodoc:
249
+ initialize_template_class(response)
250
+ assign_shortcuts(request, response)
251
+ initialize_current_url
252
+
253
+ log_processing unless logger.nil?
254
+ perform_action
255
+ close_session
256
+
257
+ return @response
258
+ end
259
+
260
+ # Returns an URL that has been rewritten according to the hash of +options+ (for doing a complete redirect, use redirect_to). The
261
+ # valid keys in options are specified below with an example going from "/library/books/ISBN/0743536703/show" (mapped to
262
+ # books_controller?action=show&type=ISBN&id=0743536703):
263
+ #
264
+ # .---> controller .--> action
265
+ # /library/books/ISBN/0743536703/show
266
+ # '------> '--------------> action_prefix
267
+ # controller_prefix
268
+ #
269
+ # * <tt>:controller_prefix</tt> - specifies the string before the controller name, which would be "/library" for the example.
270
+ # Called with "/shop" gives "/shop/books/ISBN/0743536703/show".
271
+ # * <tt>:controller</tt> - specifies a new controller and clears out everything after the controller name (including the action,
272
+ # the pre- and suffix, and all params), so called with "settings" gives "/library/settings/".
273
+ # * <tt>:action_prefix</tt> - specifies the string between the controller name and the action name, which would
274
+ # be "/ISBN/0743536703" for the example. Called with "/XTC/123/" gives "/library/books/XTC/123/show".
275
+ # * <tt>:action</tt> - specifies a new action, so called with "edit" gives "/library/books/ISBN/0743536703/edit"
276
+ # * <tt>:action_suffix</tt> - specifies the string after the action name, which would be empty for the example.
277
+ # Called with "/detailed" gives "/library/books/ISBN/0743536703/detailed".
278
+ # * <tt>:path_params</tt> - specifies a hash that contains keys mapping to the request parameter names. In the example,
279
+ # { "type" => "ISBN", "id" => "0743536703" } would be the path_params. It serves as another way of replacing part of
280
+ # the action_prefix or action_suffix. So passing { "type" => "XTC" } would give "/library/books/XTC/0743536703/show".
281
+ # * <tt>:id</tt> - shortcut where ":id => 5" can be used instead of specifying :path_params => { "id" => 5 }.
282
+ # Called with "123" gives "/library/books/ISBN/123/show".
283
+ # * <tt>:params</tt> - specifies a hash that represents the regular request parameters, such as { "cat" => 1,
284
+ # "origin" => "there"} that would give "?cat=1&origin=there". Called with { "temporary" => 1 } in the example would give
285
+ # "/library/books/ISBN/0743536703/show?temporary=1"
286
+ # * <tt>:anchor</tt> - specifies the anchor name to be appended to the path. Called with "x14" would give
287
+ # "/library/books/ISBN/0743536703/show#x14"
288
+ #
289
+ # Naturally, you can combine multiple options in a single redirect. Examples:
290
+ #
291
+ # redirect_to(:controller_prefix => "/shop", :controller => "settings")
292
+ # redirect_to(:action => "edit", :id => 3425)
293
+ # redirect_to(:action => "edit", :path_params => { "type" => "XTC"}, :params => { "temp" => 1})
294
+ # redirect_to(:action => "publish", :action_prefix => "/published", :anchor => "x14")
295
+ #
296
+ # Instead of passing an options hash, you can also pass a method reference in the form of a symbol. Consider this example:
297
+ #
298
+ # class WeblogController < ActionController::Base
299
+ # def update
300
+ # # do some update
301
+ # redirect_to :dashboard_url
302
+ # end
303
+ #
304
+ # protected
305
+ # def dashboard_url
306
+ # url_for :controller => (@project.active? ? "project" : "account"), :action => "dashboard"
307
+ # end
308
+ # end
309
+ def url_for(options = {}, *parameters_for_method_reference) #:doc:
310
+ case options
311
+ when String then options
312
+ when Symbol then send(options, *parameters_for_method_reference)
313
+ when Hash then @url.rewrite(rewrite_options(options))
314
+ end
315
+ end
316
+
317
+ # Converts the class name from something like "OneModule::TwoModule::NeatController" to "NeatController".
318
+ def controller_class_name
319
+ self.class.name.split("::").last
320
+ end
321
+
322
+ # Converts the class name from something like "OneModule::TwoModule::NeatController" to "neat".
323
+ def controller_name
324
+ controller_class_name.sub(/Controller/, "").gsub(/([a-z])([A-Z])/) { |s| $1 + "_" + $2.downcase }.downcase
325
+ end
326
+
327
+ # Returns the name of the action this controller is processing.
328
+ def action_name
329
+ @params["action"] || "index"
330
+ end
331
+
332
+ protected
333
+ # Renders the template specified by <tt>template_name</tt>, which defaults to the name of the current controller and action.
334
+ # So calling +render+ in WeblogController#show will attempt to render "#{template_root}/weblog/show.rhtml" or
335
+ # "#{template_root}/weblog/show.rxml" (in that order). The template_root is set on the ActionController::Base class and is
336
+ # shared by all controllers. It's also possible to pass a status code using the second parameter. This defaults to "200 OK",
337
+ # but can be changed, such as by calling <tt>render("weblog/error", "500 Error")</tt>.
338
+ def render(template_name = nil, status = nil) #:doc:
339
+ render_file(template_name || "#{controller_name}/#{action_name}", status, true)
340
+ end
341
+
342
+ # Works like render, but instead of requiring a full template name, you can get by with specifying the action name. So calling
343
+ # <tt>render_action "show_many"</tt> in WeblogController#display will render "#{template_root}/weblog/show_many.rhtml" or
344
+ # "#{template_root}/weblog/show_many.rxml".
345
+ def render_action(action_name, status = nil) #:doc:
346
+ render "#{controller_name}/#{action_name}", status
347
+ end
348
+
349
+ # Works like render, but disregards the template_root and requires a full path to the template that needs to be rendered. Can be
350
+ # used like <tt>render_file "/Users/david/Code/Ruby/template"</tt> to render "/Users/david/Code/Ruby/template.rhtml" or
351
+ # "/Users/david/Code/Ruby/template.rxml".
352
+ def render_file(template_path, status = nil, use_full_path = false) #:doc:
353
+ assert_existance_of_template_file(template_path) if use_full_path
354
+ logger.info("Rendering #{template_path} (#{status || DEFAULT_RENDER_STATUS_CODE})") unless logger.nil?
355
+
356
+ add_variables_to_assigns
357
+ render_text(@template.render_file(template_path, use_full_path), status)
358
+ end
359
+
360
+ # Renders the +template+ string, which is useful for rendering short templates you don't want to bother having a file for. So
361
+ # you'd call <tt>render_template "Hello, <%= @user.name %>"</tt> to greet the current user. Or if you want to render as Builder
362
+ # template, you could do <tt>render_template "xml.h1 @user.name", nil, "rxml"</tt>.
363
+ def render_template(template, status = nil, type = "rhtml") #:doc:
364
+ add_variables_to_assigns
365
+ render_text(@template.render_template(type, template), status)
366
+ end
367
+
368
+ # Renders the +text+ string without parsing it through any template engine. Useful for rendering static information as it's
369
+ # considerably faster than rendering through the template engine.
370
+ # Use block for response body if provided (useful for deferred rendering or streaming output).
371
+ def render_text(text = nil, status = nil, &block) #:doc:
372
+ add_variables_to_assigns
373
+ @response.headers["Status"] = status || DEFAULT_RENDER_STATUS_CODE
374
+ @response.body = block_given? ? block : text
375
+ @performed_render = true
376
+ end
377
+
378
+ # Sends the file by streaming it 4096 bytes at a time. This way the
379
+ # whole file doesn't need to be read into memory at once. This makes
380
+ # it feasible to send even large files.
381
+ #
382
+ # Be careful to sanitize the path parameter if it coming from a web
383
+ # page. send_file(@params['path'] allows a malicious user to
384
+ # download any file on your server.
385
+ #
386
+ # Options:
387
+ # * <tt>:filename</tt> - specifies the filename the browser will see.
388
+ # Defaults to File.basename(path).
389
+ # * <tt>:type</tt> - specifies an HTTP content type.
390
+ # Defaults to 'application/octet-stream'.
391
+ # * <tt>:disposition</tt> - specifies whether the file will be shown inline or downloaded.
392
+ # Valid values are 'inline' and 'attachment' (default).
393
+ # * <tt>:buffer_size</tt> - specifies size (in bytes) of the buffer used to stream the file.
394
+ # Defaults to 4096.
395
+ #
396
+ # The default Content-Type and Content-Disposition headers are
397
+ # set to download arbitrary binary files in as many browsers as
398
+ # possible. IE versions 4, 5, 5.5, and 6 are all known to have
399
+ # a variety of quirks (especially when downloading over SSL).
400
+ #
401
+ # Simple download:
402
+ # send_file '/path/to.zip'
403
+ #
404
+ # Show a JPEG in browser:
405
+ # send_file '/path/to.jpeg', :type => 'image/jpeg', :disposition => 'inline'
406
+ #
407
+ # Read about the other Content-* HTTP headers if you'd like to
408
+ # provide the user with more information (such as Content-Description).
409
+ # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11
410
+ #
411
+ # Also be aware that the document may be cached by proxies and browsers.
412
+ # The Pragma and Cache-Control headers declare how the file may be cached
413
+ # by intermediaries. They default to require clients to validate with
414
+ # the server before releasing cached responses. See
415
+ # http://www.mnot.net/cache_docs/ for an overview of web caching and
416
+ # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
417
+ # for the Cache-Control header spec.
418
+ def send_file(path, options = {})
419
+ options = {
420
+ :filename => File.basename(path),
421
+ :type => 'application/octet_stream',
422
+ :disposition => 'attachment',
423
+ :buffer_size => 4096
424
+ }.merge(options)
425
+
426
+ # Internet Explorer cache workaround.
427
+ if @request.env['HTTP_USER_AGENT'] =~ /msie/i
428
+ @headers['Pragma'] = ''
429
+ @headers['Cache-Control'] = ''
430
+
431
+ # HTTP 1.1 headers require strict validation with server before
432
+ # releasing a cached response to client.
433
+ else
434
+ @headers['Pragma'] = 'no-cache'
435
+ @headers['Cache-Control'] = 'no-cache, must-revalidate'
436
+ end
437
+
438
+ # HTTP 1.0 headers for cache expiry.
439
+ @headers['Last-Modified'] = CGI.rfc1123_date(File.mtime(path))
440
+ @headers['Expires'] = CGI.rfc1123_date(Time.now)
441
+
442
+ # HTTP Content headers.
443
+ @headers['Content-Type'] = options[:type]
444
+ @headers['Content-Disposition'] = "#{options[:disposition]}; filename=\"#{options[:filename]}\""
445
+ @headers['Content-Length'] = File.size(path)
446
+ @headers['Content-Transfer-Encoding'] = 'binary'
447
+
448
+ logger.info("Sending file #{path}") unless logger.nil?
449
+
450
+ render_text do
451
+ File.open(path, 'rb') do |file|
452
+ while buf = file.read(options[:buffer_size])
453
+ print buf
454
+ end
455
+ end
456
+ end
457
+ end
458
+
459
+ def rewrite_options(options)
460
+ if defaults = default_url_options(options)
461
+ defaults.merge(options)
462
+ else
463
+ options
464
+ end
465
+ end
466
+
467
+ # Overwrite to implement a number of default options that all url_for-based methods will use. The default options should come in
468
+ # the form of a hash, just like the one you would use for url_for directly. Example:
469
+ #
470
+ # def default_url_options(options)
471
+ # { :controller_prefix => @project.active? ? "projects/" : "accounts/" }
472
+ # end
473
+ #
474
+ # As you can infer from the example, this is mostly useful for situations where you want to centralize dynamic decisions about the
475
+ # urls as they stem from the business domain. Please note that any individual url_for call can always override the defaults set
476
+ # by this method.
477
+ def default_url_options(options) #:doc:
478
+ end
479
+
480
+ # Redirects the browser to an URL that has been rewritten according to the hash of +options+ using a "302 Moved" HTTP header.
481
+ # See url_for for a description of the valid options.
482
+ def redirect_to(options = {}, *parameters_for_method_reference) #:doc:
483
+ if parameters_for_method_reference.empty?
484
+ @response.redirected_to = options
485
+ redirect_to_url(url_for(options))
486
+ else
487
+ @response.redirected_to, @response.redirected_to_method_params = options, parameters_for_method_reference
488
+ redirect_to_url(url_for(options, *parameters_for_method_reference))
489
+ end
490
+ end
491
+
492
+ # Redirects the browser to the specified <tt>path</tt> within the current host (specified with a leading /). Used to sidestep
493
+ # the URL rewriting and go directly to a known path. Example: <tt>redirect_to_path "/images/screenshot.jpg"</tt>.
494
+ def redirect_to_path(path) #:doc:
495
+ redirect_to_url(@request.protocol + @request.host_with_port + path)
496
+ end
497
+
498
+ # Redirects the browser to the specified <tt>url</tt>. Used to redirect outside of the current application. Example:
499
+ # <tt>redirect_to_url "http://www.rubyonrails.org"</tt>.
500
+ def redirect_to_url(url) #:doc:
501
+ logger.info("Redirected to #{url}") unless logger.nil?
502
+ @response.redirect(url)
503
+ @performed_redirect = true
504
+ end
505
+
506
+ # Creates a new cookie that is sent along-side the next render or redirect command. API is the same as for CGI::Cookie.
507
+ # Examples:
508
+ #
509
+ # cookie("name", "value1", "value2", ...)
510
+ # cookie("name" => "name", "value" => "value")
511
+ # cookie('name' => 'name',
512
+ # 'value' => ['value1', 'value2', ...],
513
+ # 'path' => 'path', # optional
514
+ # 'domain' => 'domain', # optional
515
+ # 'expires' => Time.now, # optional
516
+ # 'secure' => true # optional
517
+ # )
518
+ def cookie(*options) #:doc:
519
+ @response.headers["cookie"] << CGI::Cookie.new(*options)
520
+ end
521
+
522
+ # Resets the session by clearsing out all the objects stored within and initializing a new session object.
523
+ def reset_session #:doc:
524
+ @request.reset_session
525
+ @session = @request.session
526
+ @response.session = @session
527
+ end
528
+
529
+ private
530
+ def initialize_template_class(response)
531
+ begin
532
+ response.template = template_class.new(template_root, {}, self)
533
+ rescue
534
+ raise "You must assign a template class through ActionController.template_class= before processing a request"
535
+ end
536
+
537
+ @performed_render = @performed_redirect = false
538
+ end
539
+
540
+ def assign_shortcuts(request, response)
541
+ @request, @params, @cookies = request, request.parameters, request.cookies
542
+
543
+ @response = response
544
+ @response.session = request.session
545
+
546
+ @session = @response.session
547
+ @template = @response.template
548
+ @assigns = @response.template.assigns
549
+ @headers = @response.headers
550
+ end
551
+
552
+ def initialize_current_url
553
+ @url = UrlRewriter.new(@request, controller_name, action_name)
554
+ end
555
+
556
+ def log_processing
557
+ logger.info "\n\nProcessing #{controller_class_name}\##{action_name} (for #{request_origin})"
558
+ logger.info " Parameters: #{@params.inspect}"
559
+ end
560
+
561
+ def perform_action
562
+ if action_methods.include?(action_name)
563
+ send(action_name)
564
+ render unless @performed_render || @performed_redirect
565
+ elsif template_exists? && template_public?
566
+ render
567
+ else
568
+ raise UnknownAction, "No action responded to #{action_name}", caller
569
+ end
570
+ end
571
+
572
+ def action_methods
573
+ action_controller_classes = self.class.ancestors.reject{ |a| [Object, Kernel].include?(a) }
574
+ action_controller_classes.inject([]) { |action_methods, klass| action_methods + klass.instance_methods(false) }
575
+ end
576
+
577
+ def add_variables_to_assigns
578
+ add_instance_variables_to_assigns
579
+ add_class_variables_to_assigns if view_controller_internals
580
+ end
581
+
582
+ def add_instance_variables_to_assigns
583
+ protected_variables_cache = protected_instance_variables
584
+ instance_variables.each do |var|
585
+ next if protected_variables_cache.include?(var)
586
+ @assigns[var[1..-1]] = instance_variable_get(var)
587
+ end
588
+ end
589
+
590
+ def add_class_variables_to_assigns
591
+ %w( template_root logger template_class ignore_missing_templates ).each do |cvar|
592
+ @assigns[cvar] = self.send(cvar)
593
+ end
594
+ end
595
+
596
+ def protected_instance_variables
597
+ if view_controller_internals
598
+ [ "@assigns", "@performed_redirect", "@performed_render" ]
599
+ else
600
+ [ "@assigns", "@performed_redirect", "@performed_render", "@request", "@response", "@session", "@cookies", "@template" ]
601
+ end
602
+ end
603
+
604
+ def request_origin
605
+ "#{@request.remote_addr} at #{Time.now.to_s}"
606
+ end
607
+
608
+ def close_session
609
+ @session.close unless @session.nil? || Hash === @session
610
+ end
611
+
612
+ def template_exists?(template_name = "#{controller_name}/#{action_name}")
613
+ @template.file_exists?(template_name)
614
+ end
615
+
616
+ def template_public?(template_name = "#{controller_name}/#{action_name}")
617
+ @template.file_public?(template_name)
618
+ end
619
+
620
+ def assert_existance_of_template_file(template_name)
621
+ unless template_exists?(template_name) || ignore_missing_templates
622
+ raise(MissingTemplate, "Couldn't find #{template_name}")
623
+ end
624
+ end
625
+ end
626
+ end