actionpack 3.0.20 → 3.1.0.beta1

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 (161) hide show
  1. data/CHANGELOG +88 -142
  2. data/MIT-LICENSE +1 -1
  3. data/README.rdoc +5 -6
  4. data/lib/abstract_controller.rb +1 -0
  5. data/lib/abstract_controller/asset_paths.rb +2 -2
  6. data/lib/abstract_controller/base.rb +24 -19
  7. data/lib/abstract_controller/callbacks.rb +19 -19
  8. data/lib/abstract_controller/helpers.rb +11 -13
  9. data/lib/abstract_controller/layouts.rb +4 -5
  10. data/lib/abstract_controller/railties/routes_helpers.rb +18 -0
  11. data/lib/abstract_controller/rendering.rb +34 -31
  12. data/lib/abstract_controller/url_for.rb +27 -0
  13. data/lib/abstract_controller/view_paths.rb +31 -6
  14. data/lib/action_controller.rb +5 -3
  15. data/lib/action_controller/base.rb +15 -16
  16. data/lib/action_controller/caching.rb +2 -2
  17. data/lib/action_controller/caching/actions.rb +11 -12
  18. data/lib/action_controller/caching/fragments.rb +41 -19
  19. data/lib/action_controller/caching/pages.rb +3 -9
  20. data/lib/action_controller/caching/sweeping.rb +0 -1
  21. data/lib/action_controller/deprecated.rb +1 -1
  22. data/lib/action_controller/log_subscriber.rb +1 -1
  23. data/lib/action_controller/metal.rb +78 -20
  24. data/lib/action_controller/metal/compatibility.rb +0 -9
  25. data/lib/action_controller/metal/conditional_get.rb +9 -9
  26. data/lib/action_controller/metal/data_streaming.rb +145 -0
  27. data/lib/action_controller/metal/force_ssl.rb +35 -0
  28. data/lib/action_controller/metal/head.rb +1 -1
  29. data/lib/action_controller/metal/helpers.rb +37 -44
  30. data/lib/action_controller/metal/hide_actions.rb +2 -3
  31. data/lib/action_controller/metal/http_authentication.rb +41 -38
  32. data/lib/action_controller/metal/implicit_render.rb +13 -13
  33. data/lib/action_controller/metal/instrumentation.rb +2 -2
  34. data/lib/action_controller/metal/mime_responds.rb +25 -19
  35. data/lib/action_controller/metal/params_wrapper.rb +224 -0
  36. data/lib/action_controller/metal/redirecting.rb +6 -2
  37. data/lib/action_controller/metal/renderers.rb +50 -36
  38. data/lib/action_controller/metal/rendering.rb +34 -25
  39. data/lib/action_controller/metal/request_forgery_protection.rb +18 -36
  40. data/lib/action_controller/metal/responder.rb +47 -12
  41. data/lib/action_controller/metal/streaming.rb +244 -138
  42. data/lib/action_controller/metal/testing.rb +0 -9
  43. data/lib/action_controller/metal/url_for.rb +12 -14
  44. data/lib/action_controller/railtie.rb +19 -37
  45. data/lib/action_controller/railties/paths.rb +24 -0
  46. data/lib/action_controller/record_identifier.rb +4 -10
  47. data/lib/action_controller/test_case.rb +36 -19
  48. data/lib/action_controller/vendor/html-scanner/html/node.rb +5 -5
  49. data/lib/action_controller/vendor/html-scanner/html/sanitizer.rb +3 -3
  50. data/lib/action_controller/vendor/html-scanner/html/selector.rb +2 -0
  51. data/lib/action_dispatch.rb +4 -1
  52. data/lib/action_dispatch/http/cache.rb +5 -32
  53. data/lib/action_dispatch/http/filter_parameters.rb +3 -1
  54. data/lib/action_dispatch/http/mime_negotiation.rb +22 -3
  55. data/lib/action_dispatch/http/mime_type.rb +45 -5
  56. data/lib/action_dispatch/http/rack_cache.rb +58 -0
  57. data/lib/action_dispatch/http/request.rb +27 -41
  58. data/lib/action_dispatch/http/response.rb +56 -54
  59. data/lib/action_dispatch/http/upload.rb +1 -11
  60. data/lib/action_dispatch/http/url.rb +102 -42
  61. data/lib/action_dispatch/middleware/callbacks.rb +8 -25
  62. data/lib/action_dispatch/middleware/closed_error.rb +7 -0
  63. data/lib/action_dispatch/middleware/cookies.rb +37 -15
  64. data/lib/action_dispatch/middleware/flash.rb +80 -11
  65. data/lib/action_dispatch/middleware/params_parser.rb +2 -2
  66. data/lib/action_dispatch/middleware/reloader.rb +76 -0
  67. data/lib/action_dispatch/middleware/session/abstract_store.rb +56 -226
  68. data/lib/action_dispatch/middleware/session/cookie_store.rb +20 -44
  69. data/lib/action_dispatch/middleware/session/mem_cache_store.rb +7 -46
  70. data/lib/action_dispatch/middleware/show_exceptions.rb +15 -2
  71. data/lib/action_dispatch/middleware/stack.rb +50 -17
  72. data/lib/action_dispatch/middleware/static.rb +41 -29
  73. data/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb +3 -3
  74. data/lib/action_dispatch/middleware/templates/rescues/_trace.erb +3 -3
  75. data/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb +3 -3
  76. data/lib/action_dispatch/middleware/templates/rescues/layout.erb +4 -2
  77. data/lib/action_dispatch/middleware/templates/rescues/template_error.erb +2 -6
  78. data/lib/action_dispatch/railtie.rb +8 -0
  79. data/lib/action_dispatch/routing.rb +13 -1
  80. data/lib/action_dispatch/routing/mapper.rb +345 -227
  81. data/lib/action_dispatch/routing/polymorphic_routes.rb +33 -13
  82. data/lib/action_dispatch/routing/redirection.rb +110 -0
  83. data/lib/action_dispatch/routing/route.rb +15 -13
  84. data/lib/action_dispatch/routing/route_set.rb +116 -90
  85. data/lib/action_dispatch/routing/routes_proxy.rb +35 -0
  86. data/lib/action_dispatch/routing/url_for.rb +25 -1
  87. data/lib/action_dispatch/testing/assertions/response.rb +8 -10
  88. data/lib/action_dispatch/testing/assertions/routing.rb +15 -15
  89. data/lib/action_dispatch/testing/assertions/selector.rb +13 -220
  90. data/lib/action_dispatch/testing/integration.rb +37 -28
  91. data/lib/action_dispatch/testing/performance_test.rb +1 -3
  92. data/lib/action_dispatch/testing/test_process.rb +1 -1
  93. data/lib/action_dispatch/testing/test_request.rb +9 -3
  94. data/lib/action_dispatch/testing/test_response.rb +4 -111
  95. data/lib/action_pack.rb +1 -1
  96. data/lib/action_pack/version.rb +3 -3
  97. data/lib/action_view.rb +39 -24
  98. data/lib/action_view/base.rb +61 -86
  99. data/lib/action_view/buffers.rb +43 -0
  100. data/lib/action_view/context.rb +21 -24
  101. data/lib/action_view/flows.rb +79 -0
  102. data/lib/action_view/helpers.rb +8 -6
  103. data/lib/action_view/helpers/active_model_helper.rb +0 -23
  104. data/lib/action_view/helpers/asset_paths.rb +79 -0
  105. data/lib/action_view/helpers/asset_tag_helper.rb +30 -500
  106. data/lib/action_view/helpers/asset_tag_helpers/asset_include_tag.rb +147 -0
  107. data/lib/action_view/helpers/asset_tag_helpers/asset_paths.rb +101 -0
  108. data/lib/action_view/helpers/asset_tag_helpers/javascript_tag_helpers.rb +200 -0
  109. data/lib/action_view/helpers/asset_tag_helpers/stylesheet_tag_helpers.rb +152 -0
  110. data/lib/action_view/helpers/atom_feed_helper.rb +2 -2
  111. data/lib/action_view/helpers/cache_helper.rb +11 -19
  112. data/lib/action_view/helpers/capture_helper.rb +19 -8
  113. data/lib/action_view/helpers/controller_helper.rb +21 -0
  114. data/lib/action_view/helpers/csrf_helper.rb +22 -4
  115. data/lib/action_view/helpers/date_helper.rb +36 -22
  116. data/lib/action_view/helpers/form_helper.rb +199 -113
  117. data/lib/action_view/helpers/form_options_helper.rb +10 -11
  118. data/lib/action_view/helpers/form_tag_helper.rb +94 -22
  119. data/lib/action_view/helpers/javascript_helper.rb +24 -107
  120. data/lib/action_view/helpers/number_helper.rb +36 -33
  121. data/lib/action_view/helpers/output_safety_helper.rb +38 -0
  122. data/lib/action_view/helpers/record_tag_helper.rb +6 -6
  123. data/lib/action_view/helpers/rendering_helper.rb +90 -0
  124. data/lib/action_view/helpers/sanitize_helper.rb +2 -2
  125. data/lib/action_view/helpers/sprockets_helper.rb +69 -0
  126. data/lib/action_view/helpers/tag_helper.rb +34 -12
  127. data/lib/action_view/helpers/text_helper.rb +30 -145
  128. data/lib/action_view/helpers/translation_helper.rb +10 -17
  129. data/lib/action_view/helpers/url_helper.rb +70 -67
  130. data/lib/action_view/locale/en.yml +1 -1
  131. data/lib/action_view/lookup_context.rb +36 -14
  132. data/lib/action_view/{paths.rb → path_set.rb} +9 -8
  133. data/lib/action_view/railtie.rb +12 -4
  134. data/lib/action_view/renderer/abstract_renderer.rb +36 -0
  135. data/lib/action_view/{render/partials.rb → renderer/partial_renderer.rb} +147 -146
  136. data/lib/action_view/renderer/renderer.rb +54 -0
  137. data/lib/action_view/renderer/streaming_template_renderer.rb +106 -0
  138. data/lib/action_view/renderer/template_renderer.rb +74 -0
  139. data/lib/action_view/template.rb +91 -54
  140. data/lib/action_view/template/error.rb +11 -8
  141. data/lib/action_view/template/handler.rb +9 -1
  142. data/lib/action_view/template/handlers.rb +9 -9
  143. data/lib/action_view/template/handlers/builder.rb +4 -4
  144. data/lib/action_view/template/handlers/erb.rb +21 -41
  145. data/lib/action_view/template/resolver.rb +171 -57
  146. data/lib/action_view/template/text.rb +0 -4
  147. data/lib/action_view/test_case.rb +32 -16
  148. data/lib/action_view/testing/resolvers.rb +16 -10
  149. data/lib/sprockets/railtie.rb +100 -0
  150. metadata +162 -140
  151. checksums.yaml +0 -7
  152. data/lib/action_controller/deprecated/base.rb +0 -143
  153. data/lib/action_controller/deprecated/dispatcher.rb +0 -28
  154. data/lib/action_controller/deprecated/url_writer.rb +0 -14
  155. data/lib/action_dispatch/routing/deprecated_mapper.rb +0 -525
  156. data/lib/action_view/helpers/prototype_helper.rb +0 -851
  157. data/lib/action_view/helpers/raw_output_helper.rb +0 -18
  158. data/lib/action_view/helpers/scriptaculous_helper.rb +0 -263
  159. data/lib/action_view/render/layouts.rb +0 -83
  160. data/lib/action_view/render/rendering.rb +0 -67
  161. data/lib/action_view/template/handlers/rjs.rb +0 -17
@@ -1,851 +0,0 @@
1
- require 'set'
2
- require 'active_support/json'
3
- require 'active_support/core_ext/object/blank'
4
-
5
- module ActionView
6
- # = Action View Prototype Helpers
7
- module Helpers
8
- # Prototype[http://www.prototypejs.org/] is a JavaScript library that provides
9
- # DOM[http://en.wikipedia.org/wiki/Document_Object_Model] manipulation,
10
- # Ajax[http://www.adaptivepath.com/publications/essays/archives/000385.php]
11
- # functionality, and more traditional object-oriented facilities for JavaScript.
12
- # This module provides a set of helpers to make it more convenient to call
13
- # functions from Prototype using Rails, including functionality to call remote
14
- # Rails methods (that is, making a background request to a Rails action) using Ajax.
15
- # This means that you can call actions in your controllers without
16
- # reloading the page, but still update certain parts of it using
17
- # injections into the DOM. A common use case is having a form that adds
18
- # a new element to a list without reloading the page or updating a shopping
19
- # cart total when a new item is added.
20
- #
21
- # == Usage
22
- # To be able to use these helpers, you must first include the Prototype
23
- # JavaScript framework in your pages.
24
- #
25
- # javascript_include_tag 'prototype'
26
- #
27
- # (See the documentation for
28
- # ActionView::Helpers::JavaScriptHelper for more information on including
29
- # this and other JavaScript files in your Rails templates.)
30
- #
31
- # Now you're ready to call a remote action either through a link...
32
- #
33
- # link_to_remote "Add to cart",
34
- # :url => { :action => "add", :id => product.id },
35
- # :update => { :success => "cart", :failure => "error" }
36
- #
37
- # ...through a form...
38
- #
39
- # <%= form_remote_tag :url => '/shipping' do -%>
40
- # <div><%= submit_tag 'Recalculate Shipping' %></div>
41
- # <% end -%>
42
- #
43
- # As you can see, there are numerous ways to use Prototype's Ajax functions (and actually more than
44
- # are listed here); check out the documentation for each method to find out more about its usage and options.
45
- #
46
- # === Common Options
47
- # See link_to_remote for documentation of options common to all Ajax
48
- # helpers; any of the options specified by link_to_remote can be used
49
- # by the other helpers.
50
- #
51
- # == Designing your Rails actions for Ajax
52
- # When building your action handlers (that is, the Rails actions that receive your background requests), it's
53
- # important to remember a few things. First, whatever your action would normally return to the browser, it will
54
- # return to the Ajax call. As such, you typically don't want to render with a layout. This call will cause
55
- # the layout to be transmitted back to your page, and, if you have a full HTML/CSS, will likely mess a lot of things up.
56
- # You can turn the layout off on particular actions by doing the following:
57
- #
58
- # class SiteController < ActionController::Base
59
- # layout "standard", :except => [:ajax_method, :more_ajax, :another_ajax]
60
- # end
61
- #
62
- # Optionally, you could do this in the method you wish to lack a layout:
63
- #
64
- # render :layout => false
65
- #
66
- # You can tell the type of request from within your action using the <tt>request.xhr?</tt> (XmlHttpRequest, the
67
- # method that Ajax uses to make background requests) method.
68
- # def name
69
- # # Is this an XmlHttpRequest request?
70
- # if (request.xhr?)
71
- # render :text => @name.to_s
72
- # else
73
- # # No? Then render an action.
74
- # render :action => 'view_attribute', :attr => @name
75
- # end
76
- # end
77
- #
78
- # The else clause can be left off and the current action will render with full layout and template. An extension
79
- # to this solution was posted to Ryan Heneise's blog at ArtOfMission["http://www.artofmission.com/"].
80
- #
81
- # layout proc{ |c| c.request.xhr? ? false : "application" }
82
- #
83
- # Dropping this in your ApplicationController turns the layout off for every request that is an "xhr" request.
84
- #
85
- # If you are just returning a little data or don't want to build a template for your output, you may opt to simply
86
- # render text output, like this:
87
- #
88
- # render :text => 'Return this from my method!'
89
- #
90
- # Since whatever the method returns is injected into the DOM, this will simply inject some text (or HTML, if you
91
- # tell it to). This is usually how small updates, such updating a cart total or a file count, are handled.
92
- #
93
- # == Updating multiple elements
94
- # See JavaScriptGenerator for information on updating multiple elements
95
- # on the page in an Ajax response.
96
- module PrototypeHelper
97
- CALLBACKS = Set.new([ :create, :uninitialized, :loading, :loaded,
98
- :interactive, :complete, :failure, :success ] +
99
- (100..599).to_a)
100
- AJAX_OPTIONS = Set.new([ :before, :after, :condition, :url,
101
- :asynchronous, :method, :insertion, :position,
102
- :form, :with, :update, :script, :type ]).merge(CALLBACKS)
103
-
104
- # Returns the JavaScript needed for a remote function.
105
- # See the link_to_remote documentation at http://github.com/rails/prototype_legacy_helper as it takes the same arguments.
106
- #
107
- # Example:
108
- # # Generates: <select id="options" onchange="new Ajax.Updater('options',
109
- # # '/testing/update_options', {asynchronous:true, evalScripts:true})">
110
- # <select id="options" onchange="<%= remote_function(:update => "options",
111
- # :url => { :action => :update_options }) %>">
112
- # <option value="0">Hello</option>
113
- # <option value="1">World</option>
114
- # </select>
115
- def remote_function(options)
116
- javascript_options = options_for_ajax(options)
117
-
118
- update = ''
119
- if options[:update] && options[:update].is_a?(Hash)
120
- update = []
121
- update << "success:'#{options[:update][:success]}'" if options[:update][:success]
122
- update << "failure:'#{options[:update][:failure]}'" if options[:update][:failure]
123
- update = '{' + update.join(',') + '}'
124
- elsif options[:update]
125
- update << "'#{options[:update]}'"
126
- end
127
-
128
- function = update.empty? ?
129
- "new Ajax.Request(" :
130
- "new Ajax.Updater(#{update}, "
131
-
132
- url_options = options[:url]
133
- function << "'#{html_escape(escape_javascript(url_for(url_options)))}'"
134
- function << ", #{javascript_options})"
135
-
136
- function = "#{options[:before]}; #{function}" if options[:before]
137
- function = "#{function}; #{options[:after]}" if options[:after]
138
- function = "if (#{options[:condition]}) { #{function}; }" if options[:condition]
139
- function = "if (confirm('#{escape_javascript(options[:confirm])}')) { #{function}; }" if options[:confirm]
140
-
141
- return function.html_safe
142
- end
143
-
144
- # All the methods were moved to GeneratorMethods so that
145
- # #include_helpers_from_context has nothing to overwrite.
146
- class JavaScriptGenerator #:nodoc:
147
- def initialize(context, &block) #:nodoc:
148
- @context, @lines = context, []
149
- include_helpers_from_context
150
- @context.with_output_buffer(@lines) do
151
- @context.instance_exec(self, &block)
152
- end
153
- end
154
-
155
- private
156
- def include_helpers_from_context
157
- extend @context.helpers if @context.respond_to?(:helpers)
158
- extend GeneratorMethods
159
- end
160
-
161
- # JavaScriptGenerator generates blocks of JavaScript code that allow you
162
- # to change the content and presentation of multiple DOM elements. Use
163
- # this in your Ajax response bodies, either in a <tt>\<script></tt> tag or as plain
164
- # JavaScript sent with a Content-type of "text/javascript".
165
- #
166
- # Create new instances with PrototypeHelper#update_page or with
167
- # ActionController::Base#render, then call +insert_html+, +replace_html+,
168
- # +remove+, +show+, +hide+, +visual_effect+, or any other of the built-in
169
- # methods on the yielded generator in any order you like to modify the
170
- # content and appearance of the current page.
171
- #
172
- # Example:
173
- #
174
- # # Generates:
175
- # # new Element.insert("list", { bottom: "<li>Some item</li>" });
176
- # # new Effect.Highlight("list");
177
- # # ["status-indicator", "cancel-link"].each(Element.hide);
178
- # update_page do |page|
179
- # page.insert_html :bottom, 'list', "<li>#{@item.name}</li>"
180
- # page.visual_effect :highlight, 'list'
181
- # page.hide 'status-indicator', 'cancel-link'
182
- # end
183
- #
184
- #
185
- # Helper methods can be used in conjunction with JavaScriptGenerator.
186
- # When a helper method is called inside an update block on the +page+
187
- # object, that method will also have access to a +page+ object.
188
- #
189
- # Example:
190
- #
191
- # module ApplicationHelper
192
- # def update_time
193
- # page.replace_html 'time', Time.now.to_s(:db)
194
- # page.visual_effect :highlight, 'time'
195
- # end
196
- # end
197
- #
198
- # # Controller action
199
- # def poll
200
- # render(:update) { |page| page.update_time }
201
- # end
202
- #
203
- # Calls to JavaScriptGenerator not matching a helper method below
204
- # generate a proxy to the JavaScript Class named by the method called.
205
- #
206
- # Examples:
207
- #
208
- # # Generates:
209
- # # Foo.init();
210
- # update_page do |page|
211
- # page.foo.init
212
- # end
213
- #
214
- # # Generates:
215
- # # Event.observe('one', 'click', function () {
216
- # # $('two').show();
217
- # # });
218
- # update_page do |page|
219
- # page.event.observe('one', 'click') do |p|
220
- # p[:two].show
221
- # end
222
- # end
223
- #
224
- # You can also use PrototypeHelper#update_page_tag instead of
225
- # PrototypeHelper#update_page to wrap the generated JavaScript in a
226
- # <tt>\<script></tt> tag.
227
- module GeneratorMethods
228
- def to_s #:nodoc:
229
- (@lines * $/).tap do |javascript|
230
- if ActionView::Base.debug_rjs
231
- source = javascript.dup
232
- javascript.replace "try {\n#{source}\n} catch (e) "
233
- javascript << "{ alert('RJS error:\\n\\n' + e.toString()); alert('#{source.gsub('\\','\0\0').gsub(/\r\n|\n|\r/, "\\n").gsub(/["']/) { |m| "\\#{m}" }}'); throw e }"
234
- end
235
- end
236
- end
237
-
238
- # Returns a element reference by finding it through +id+ in the DOM. This element can then be
239
- # used for further method calls. Examples:
240
- #
241
- # page['blank_slate'] # => $('blank_slate');
242
- # page['blank_slate'].show # => $('blank_slate').show();
243
- # page['blank_slate'].show('first').up # => $('blank_slate').show('first').up();
244
- #
245
- # You can also pass in a record, which will use ActionController::RecordIdentifier.dom_id to lookup
246
- # the correct id:
247
- #
248
- # page[@post] # => $('post_45')
249
- # page[Post.new] # => $('new_post')
250
- def [](id)
251
- case id
252
- when String, Symbol, NilClass
253
- JavaScriptElementProxy.new(self, id)
254
- else
255
- JavaScriptElementProxy.new(self, ActionController::RecordIdentifier.dom_id(id))
256
- end
257
- end
258
-
259
- # Returns an object whose <tt>to_json</tt> evaluates to +code+. Use this to pass a literal JavaScript
260
- # expression as an argument to another JavaScriptGenerator method.
261
- def literal(code)
262
- ::ActiveSupport::JSON::Variable.new(code.to_s)
263
- end
264
-
265
- # Returns a collection reference by finding it through a CSS +pattern+ in the DOM. This collection can then be
266
- # used for further method calls. Examples:
267
- #
268
- # page.select('p') # => $$('p');
269
- # page.select('p.welcome b').first # => $$('p.welcome b').first();
270
- # page.select('p.welcome b').first.hide # => $$('p.welcome b').first().hide();
271
- #
272
- # You can also use prototype enumerations with the collection. Observe:
273
- #
274
- # # Generates: $$('#items li').each(function(value) { value.hide(); });
275
- # page.select('#items li').each do |value|
276
- # value.hide
277
- # end
278
- #
279
- # Though you can call the block param anything you want, they are always rendered in the
280
- # javascript as 'value, index.' Other enumerations, like collect() return the last statement:
281
- #
282
- # # Generates: var hidden = $$('#items li').collect(function(value, index) { return value.hide(); });
283
- # page.select('#items li').collect('hidden') do |item|
284
- # item.hide
285
- # end
286
- #
287
- def select(pattern)
288
- JavaScriptElementCollectionProxy.new(self, pattern)
289
- end
290
-
291
- # Inserts HTML at the specified +position+ relative to the DOM element
292
- # identified by the given +id+.
293
- #
294
- # +position+ may be one of:
295
- #
296
- # <tt>:top</tt>:: HTML is inserted inside the element, before the
297
- # element's existing content.
298
- # <tt>:bottom</tt>:: HTML is inserted inside the element, after the
299
- # element's existing content.
300
- # <tt>:before</tt>:: HTML is inserted immediately preceding the element.
301
- # <tt>:after</tt>:: HTML is inserted immediately following the element.
302
- #
303
- # +options_for_render+ may be either a string of HTML to insert, or a hash
304
- # of options to be passed to ActionView::Base#render. For example:
305
- #
306
- # # Insert the rendered 'navigation' partial just before the DOM
307
- # # element with ID 'content'.
308
- # # Generates: Element.insert("content", { before: "-- Contents of 'navigation' partial --" });
309
- # page.insert_html :before, 'content', :partial => 'navigation'
310
- #
311
- # # Add a list item to the bottom of the <ul> with ID 'list'.
312
- # # Generates: Element.insert("list", { bottom: "<li>Last item</li>" });
313
- # page.insert_html :bottom, 'list', '<li>Last item</li>'
314
- #
315
- def insert_html(position, id, *options_for_render)
316
- content = javascript_object_for(render(*options_for_render))
317
- record "Element.insert(\"#{id}\", { #{position.to_s.downcase}: #{content} });"
318
- end
319
-
320
- # Replaces the inner HTML of the DOM element with the given +id+.
321
- #
322
- # +options_for_render+ may be either a string of HTML to insert, or a hash
323
- # of options to be passed to ActionView::Base#render. For example:
324
- #
325
- # # Replace the HTML of the DOM element having ID 'person-45' with the
326
- # # 'person' partial for the appropriate object.
327
- # # Generates: Element.update("person-45", "-- Contents of 'person' partial --");
328
- # page.replace_html 'person-45', :partial => 'person', :object => @person
329
- #
330
- def replace_html(id, *options_for_render)
331
- call 'Element.update', id, render(*options_for_render)
332
- end
333
-
334
- # Replaces the "outer HTML" (i.e., the entire element, not just its
335
- # contents) of the DOM element with the given +id+.
336
- #
337
- # +options_for_render+ may be either a string of HTML to insert, or a hash
338
- # of options to be passed to ActionView::Base#render. For example:
339
- #
340
- # # Replace the DOM element having ID 'person-45' with the
341
- # # 'person' partial for the appropriate object.
342
- # page.replace 'person-45', :partial => 'person', :object => @person
343
- #
344
- # This allows the same partial that is used for the +insert_html+ to
345
- # be also used for the input to +replace+ without resorting to
346
- # the use of wrapper elements.
347
- #
348
- # Examples:
349
- #
350
- # <div id="people">
351
- # <%= render :partial => 'person', :collection => @people %>
352
- # </div>
353
- #
354
- # # Insert a new person
355
- # #
356
- # # Generates: new Insertion.Bottom({object: "Matz", partial: "person"}, "");
357
- # page.insert_html :bottom, :partial => 'person', :object => @person
358
- #
359
- # # Replace an existing person
360
- #
361
- # # Generates: Element.replace("person_45", "-- Contents of partial --");
362
- # page.replace 'person_45', :partial => 'person', :object => @person
363
- #
364
- def replace(id, *options_for_render)
365
- call 'Element.replace', id, render(*options_for_render)
366
- end
367
-
368
- # Removes the DOM elements with the given +ids+ from the page.
369
- #
370
- # Example:
371
- #
372
- # # Remove a few people
373
- # # Generates: ["person_23", "person_9", "person_2"].each(Element.remove);
374
- # page.remove 'person_23', 'person_9', 'person_2'
375
- #
376
- def remove(*ids)
377
- loop_on_multiple_args 'Element.remove', ids
378
- end
379
-
380
- # Shows hidden DOM elements with the given +ids+.
381
- #
382
- # Example:
383
- #
384
- # # Show a few people
385
- # # Generates: ["person_6", "person_13", "person_223"].each(Element.show);
386
- # page.show 'person_6', 'person_13', 'person_223'
387
- #
388
- def show(*ids)
389
- loop_on_multiple_args 'Element.show', ids
390
- end
391
-
392
- # Hides the visible DOM elements with the given +ids+.
393
- #
394
- # Example:
395
- #
396
- # # Hide a few people
397
- # # Generates: ["person_29", "person_9", "person_0"].each(Element.hide);
398
- # page.hide 'person_29', 'person_9', 'person_0'
399
- #
400
- def hide(*ids)
401
- loop_on_multiple_args 'Element.hide', ids
402
- end
403
-
404
- # Toggles the visibility of the DOM elements with the given +ids+.
405
- # Example:
406
- #
407
- # # Show a few people
408
- # # Generates: ["person_14", "person_12", "person_23"].each(Element.toggle);
409
- # page.toggle 'person_14', 'person_12', 'person_23' # Hides the elements
410
- # page.toggle 'person_14', 'person_12', 'person_23' # Shows the previously hidden elements
411
- #
412
- def toggle(*ids)
413
- loop_on_multiple_args 'Element.toggle', ids
414
- end
415
-
416
- # Displays an alert dialog with the given +message+.
417
- #
418
- # Example:
419
- #
420
- # # Generates: alert('This message is from Rails!')
421
- # page.alert('This message is from Rails!')
422
- def alert(message)
423
- call 'alert', message
424
- end
425
-
426
- # Redirects the browser to the given +location+ using JavaScript, in the same form as +url_for+.
427
- #
428
- # Examples:
429
- #
430
- # # Generates: window.location.href = "/mycontroller";
431
- # page.redirect_to(:action => 'index')
432
- #
433
- # # Generates: window.location.href = "/account/signup";
434
- # page.redirect_to(:controller => 'account', :action => 'signup')
435
- def redirect_to(location)
436
- url = location.is_a?(String) ? location : @context.url_for(location)
437
- record "window.location.href = #{url.inspect}"
438
- end
439
-
440
- # Reloads the browser's current +location+ using JavaScript
441
- #
442
- # Examples:
443
- #
444
- # # Generates: window.location.reload();
445
- # page.reload
446
- def reload
447
- record 'window.location.reload()'
448
- end
449
-
450
- # Calls the JavaScript +function+, optionally with the given +arguments+.
451
- #
452
- # If a block is given, the block will be passed to a new JavaScriptGenerator;
453
- # the resulting JavaScript code will then be wrapped inside <tt>function() { ... }</tt>
454
- # and passed as the called function's final argument.
455
- #
456
- # Examples:
457
- #
458
- # # Generates: Element.replace(my_element, "My content to replace with.")
459
- # page.call 'Element.replace', 'my_element', "My content to replace with."
460
- #
461
- # # Generates: alert('My message!')
462
- # page.call 'alert', 'My message!'
463
- #
464
- # # Generates:
465
- # # my_method(function() {
466
- # # $("one").show();
467
- # # $("two").hide();
468
- # # });
469
- # page.call(:my_method) do |p|
470
- # p[:one].show
471
- # p[:two].hide
472
- # end
473
- def call(function, *arguments, &block)
474
- record "#{function}(#{arguments_for_call(arguments, block)})"
475
- end
476
-
477
- # Assigns the JavaScript +variable+ the given +value+.
478
- #
479
- # Examples:
480
- #
481
- # # Generates: my_string = "This is mine!";
482
- # page.assign 'my_string', 'This is mine!'
483
- #
484
- # # Generates: record_count = 33;
485
- # page.assign 'record_count', 33
486
- #
487
- # # Generates: tabulated_total = 47
488
- # page.assign 'tabulated_total', @total_from_cart
489
- #
490
- def assign(variable, value)
491
- record "#{variable} = #{javascript_object_for(value)}"
492
- end
493
-
494
- # Writes raw JavaScript to the page.
495
- #
496
- # Example:
497
- #
498
- # page << "alert('JavaScript with Prototype.');"
499
- def <<(javascript)
500
- @lines << javascript
501
- end
502
-
503
- # Executes the content of the block after a delay of +seconds+. Example:
504
- #
505
- # # Generates:
506
- # # setTimeout(function() {
507
- # # ;
508
- # # new Effect.Fade("notice",{});
509
- # # }, 20000);
510
- # page.delay(20) do
511
- # page.visual_effect :fade, 'notice'
512
- # end
513
- def delay(seconds = 1)
514
- record "setTimeout(function() {\n\n"
515
- yield
516
- record "}, #{(seconds * 1000).to_i})"
517
- end
518
-
519
- private
520
- def loop_on_multiple_args(method, ids)
521
- record(ids.size>1 ?
522
- "#{javascript_object_for(ids)}.each(#{method})" :
523
- "#{method}(#{javascript_object_for(ids.first)})")
524
- end
525
-
526
- def page
527
- self
528
- end
529
-
530
- def record(line)
531
- line = "#{line.to_s.chomp.gsub(/\;\z/, '')};"
532
- self << line
533
- line
534
- end
535
-
536
- def render(*options)
537
- with_formats(:html) do
538
- case option = options.first
539
- when Hash
540
- @context.render(*options)
541
- else
542
- option.to_s
543
- end
544
- end
545
- end
546
-
547
- def with_formats(*args)
548
- @context ? @context.update_details(:formats => args) { yield } : yield
549
- end
550
-
551
- def javascript_object_for(object)
552
- ::ActiveSupport::JSON.encode(object)
553
- end
554
-
555
- def arguments_for_call(arguments, block = nil)
556
- arguments << block_to_function(block) if block
557
- arguments.map { |argument| javascript_object_for(argument) }.join ', '
558
- end
559
-
560
- def block_to_function(block)
561
- generator = self.class.new(@context, &block)
562
- literal("function() { #{generator.to_s} }")
563
- end
564
-
565
- def method_missing(method, *arguments)
566
- JavaScriptProxy.new(self, method.to_s.camelize)
567
- end
568
- end
569
- end
570
-
571
- # Yields a JavaScriptGenerator and returns the generated JavaScript code.
572
- # Use this to update multiple elements on a page in an Ajax response.
573
- # See JavaScriptGenerator for more information.
574
- #
575
- # Example:
576
- #
577
- # update_page do |page|
578
- # page.hide 'spinner'
579
- # end
580
- def update_page(&block)
581
- JavaScriptGenerator.new(view_context, &block).to_s.html_safe
582
- end
583
-
584
- # Works like update_page but wraps the generated JavaScript in a <tt>\<script></tt>
585
- # tag. Use this to include generated JavaScript in an ERb template.
586
- # See JavaScriptGenerator for more information.
587
- #
588
- # +html_options+ may be a hash of <tt>\<script></tt> attributes to be passed
589
- # to ActionView::Helpers::JavaScriptHelper#javascript_tag.
590
- def update_page_tag(html_options = {}, &block)
591
- javascript_tag update_page(&block), html_options
592
- end
593
-
594
- protected
595
- def options_for_javascript(options)
596
- if options.empty?
597
- '{}'
598
- else
599
- "{#{options.keys.map { |k| "#{k}:#{options[k]}" }.sort.join(', ')}}"
600
- end
601
- end
602
-
603
- def options_for_ajax(options)
604
- js_options = build_callbacks(options)
605
-
606
- js_options['asynchronous'] = options[:type] != :synchronous
607
- js_options['method'] = method_option_to_s(options[:method]) if options[:method]
608
- js_options['insertion'] = "'#{options[:position].to_s.downcase}'" if options[:position]
609
- js_options['evalScripts'] = options[:script].nil? || options[:script]
610
-
611
- if options[:form]
612
- js_options['parameters'] = 'Form.serialize(this)'
613
- elsif options[:submit]
614
- js_options['parameters'] = "Form.serialize('#{options[:submit]}')"
615
- elsif options[:with]
616
- js_options['parameters'] = options[:with]
617
- end
618
-
619
- if protect_against_forgery? && !options[:form]
620
- if js_options['parameters']
621
- js_options['parameters'] << " + '&"
622
- else
623
- js_options['parameters'] = "'"
624
- end
625
- js_options['parameters'] << "#{request_forgery_protection_token}=' + encodeURIComponent('#{escape_javascript form_authenticity_token}')"
626
- end
627
-
628
- options_for_javascript(js_options)
629
- end
630
-
631
- def method_option_to_s(method)
632
- (method.is_a?(String) and !method.index("'").nil?) ? method : "'#{method}'"
633
- end
634
-
635
- def build_callbacks(options)
636
- callbacks = {}
637
- options.each do |callback, code|
638
- if CALLBACKS.include?(callback)
639
- name = 'on' + callback.to_s.capitalize
640
- callbacks[name] = "function(request){#{code}}"
641
- end
642
- end
643
- callbacks
644
- end
645
- end
646
-
647
- # Converts chained method calls on DOM proxy elements into JavaScript chains
648
- class JavaScriptProxy < ActiveSupport::BasicObject #:nodoc:
649
-
650
- def initialize(generator, root = nil)
651
- @generator = generator
652
- @generator << root if root
653
- end
654
-
655
- def is_a?(klass)
656
- klass == JavaScriptProxy
657
- end
658
-
659
- private
660
- def method_missing(method, *arguments, &block)
661
- if method.to_s =~ /(.*)=$/
662
- assign($1, arguments.first)
663
- else
664
- call("#{method.to_s.camelize(:lower)}", *arguments, &block)
665
- end
666
- end
667
-
668
- def call(function, *arguments, &block)
669
- append_to_function_chain!("#{function}(#{@generator.send(:arguments_for_call, arguments, block)})")
670
- self
671
- end
672
-
673
- def assign(variable, value)
674
- append_to_function_chain!("#{variable} = #{@generator.send(:javascript_object_for, value)}")
675
- end
676
-
677
- def function_chain
678
- @function_chain ||= @generator.instance_variable_get(:@lines)
679
- end
680
-
681
- def append_to_function_chain!(call)
682
- function_chain[-1].chomp!(';')
683
- function_chain[-1] += ".#{call};"
684
- end
685
- end
686
-
687
- class JavaScriptElementProxy < JavaScriptProxy #:nodoc:
688
- def initialize(generator, id)
689
- @id = id
690
- super(generator, "$(#{::ActiveSupport::JSON.encode(id)})")
691
- end
692
-
693
- # Allows access of element attributes through +attribute+. Examples:
694
- #
695
- # page['foo']['style'] # => $('foo').style;
696
- # page['foo']['style']['color'] # => $('blank_slate').style.color;
697
- # page['foo']['style']['color'] = 'red' # => $('blank_slate').style.color = 'red';
698
- # page['foo']['style'].color = 'red' # => $('blank_slate').style.color = 'red';
699
- def [](attribute)
700
- append_to_function_chain!(attribute)
701
- self
702
- end
703
-
704
- def []=(variable, value)
705
- assign(variable, value)
706
- end
707
-
708
- def replace_html(*options_for_render)
709
- call 'update', @generator.send(:render, *options_for_render)
710
- end
711
-
712
- def replace(*options_for_render)
713
- call 'replace', @generator.send(:render, *options_for_render)
714
- end
715
-
716
- def reload(options_for_replace = {})
717
- replace(options_for_replace.merge({ :partial => @id.to_s }))
718
- end
719
-
720
- end
721
-
722
- class JavaScriptVariableProxy < JavaScriptProxy #:nodoc:
723
- def initialize(generator, variable)
724
- @variable = ::ActiveSupport::JSON::Variable.new(variable)
725
- @empty = true # only record lines if we have to. gets rid of unnecessary linebreaks
726
- super(generator)
727
- end
728
-
729
- # The JSON Encoder calls this to check for the +to_json+ method
730
- # Since it's a blank slate object, I suppose it responds to anything.
731
- def respond_to?(*)
732
- true
733
- end
734
-
735
- def as_json(options = nil)
736
- @variable
737
- end
738
-
739
- private
740
- def append_to_function_chain!(call)
741
- @generator << @variable if @empty
742
- @empty = false
743
- super
744
- end
745
- end
746
-
747
- class JavaScriptCollectionProxy < JavaScriptProxy #:nodoc:
748
- ENUMERABLE_METHODS_WITH_RETURN = [:all, :any, :collect, :map, :detect, :find, :find_all, :select, :max, :min, :partition, :reject, :sort_by, :in_groups_of, :each_slice] unless defined? ENUMERABLE_METHODS_WITH_RETURN
749
- ENUMERABLE_METHODS = ENUMERABLE_METHODS_WITH_RETURN + [:each] unless defined? ENUMERABLE_METHODS
750
- attr_reader :generator
751
- delegate :arguments_for_call, :to => :generator
752
-
753
- def initialize(generator, pattern)
754
- super(generator, @pattern = pattern)
755
- end
756
-
757
- def each_slice(variable, number, &block)
758
- if block
759
- enumerate :eachSlice, :variable => variable, :method_args => [number], :yield_args => %w(value index), :return => true, &block
760
- else
761
- add_variable_assignment!(variable)
762
- append_enumerable_function!("eachSlice(#{::ActiveSupport::JSON.encode(number)});")
763
- end
764
- end
765
-
766
- def grep(variable, pattern, &block)
767
- enumerate :grep, :variable => variable, :return => true, :method_args => [::ActiveSupport::JSON::Variable.new(pattern.inspect)], :yield_args => %w(value index), &block
768
- end
769
-
770
- def in_groups_of(variable, number, fill_with = nil)
771
- arguments = [number]
772
- arguments << fill_with unless fill_with.nil?
773
- add_variable_assignment!(variable)
774
- append_enumerable_function!("inGroupsOf(#{arguments_for_call arguments});")
775
- end
776
-
777
- def inject(variable, memo, &block)
778
- enumerate :inject, :variable => variable, :method_args => [memo], :yield_args => %w(memo value index), :return => true, &block
779
- end
780
-
781
- def pluck(variable, property)
782
- add_variable_assignment!(variable)
783
- append_enumerable_function!("pluck(#{::ActiveSupport::JSON.encode(property)});")
784
- end
785
-
786
- def zip(variable, *arguments, &block)
787
- add_variable_assignment!(variable)
788
- append_enumerable_function!("zip(#{arguments_for_call arguments}")
789
- if block
790
- function_chain[-1] += ", function(array) {"
791
- yield ::ActiveSupport::JSON::Variable.new('array')
792
- add_return_statement!
793
- @generator << '});'
794
- else
795
- function_chain[-1] += ');'
796
- end
797
- end
798
-
799
- private
800
- def method_missing(method, *arguments, &block)
801
- if ENUMERABLE_METHODS.include?(method)
802
- returnable = ENUMERABLE_METHODS_WITH_RETURN.include?(method)
803
- variable = arguments.first if returnable
804
- enumerate(method, {:variable => (arguments.first if returnable), :return => returnable, :yield_args => %w(value index)}, &block)
805
- else
806
- super
807
- end
808
- end
809
-
810
- # Options
811
- # * variable - name of the variable to set the result of the enumeration to
812
- # * method_args - array of the javascript enumeration method args that occur before the function
813
- # * yield_args - array of the javascript yield args
814
- # * return - true if the enumeration should return the last statement
815
- def enumerate(enumerable, options = {}, &block)
816
- options[:method_args] ||= []
817
- options[:yield_args] ||= []
818
- yield_args = options[:yield_args] * ', '
819
- method_args = arguments_for_call options[:method_args] # foo, bar, function
820
- method_args << ', ' unless method_args.blank?
821
- add_variable_assignment!(options[:variable]) if options[:variable]
822
- append_enumerable_function!("#{enumerable.to_s.camelize(:lower)}(#{method_args}function(#{yield_args}) {")
823
- # only yield as many params as were passed in the block
824
- yield(*options[:yield_args].collect { |p| JavaScriptVariableProxy.new(@generator, p) }[0..block.arity-1])
825
- add_return_statement! if options[:return]
826
- @generator << '});'
827
- end
828
-
829
- def add_variable_assignment!(variable)
830
- function_chain.push("var #{variable} = #{function_chain.pop}")
831
- end
832
-
833
- def add_return_statement!
834
- unless function_chain.last =~ /return/
835
- function_chain.push("return #{function_chain.pop.chomp(';')};")
836
- end
837
- end
838
-
839
- def append_enumerable_function!(call)
840
- function_chain[-1].chomp!(';')
841
- function_chain[-1] += ".#{call}"
842
- end
843
- end
844
-
845
- class JavaScriptElementCollectionProxy < JavaScriptCollectionProxy #:nodoc:\
846
- def initialize(generator, pattern)
847
- super(generator, "$$(#{::ActiveSupport::JSON.encode(pattern)})")
848
- end
849
- end
850
- end
851
- end