Froze rails gems
[depot.git] / vendor / rails / actionpack / lib / action_view / helpers / prototype_helper.rb
1 require 'set'
2
3 module ActionView
4 module Helpers
5 # Prototype[http://www.prototypejs.org/] is a JavaScript library that provides
6 # DOM[http://en.wikipedia.org/wiki/Document_Object_Model] manipulation,
7 # Ajax[http://www.adaptivepath.com/publications/essays/archives/000385.php]
8 # functionality, and more traditional object-oriented facilities for JavaScript.
9 # This module provides a set of helpers to make it more convenient to call
10 # functions from Prototype using Rails, including functionality to call remote
11 # Rails methods (that is, making a background request to a Rails action) using Ajax.
12 # This means that you can call actions in your controllers without
13 # reloading the page, but still update certain parts of it using
14 # injections into the DOM. A common use case is having a form that adds
15 # a new element to a list without reloading the page or updating a shopping
16 # cart total when a new item is added.
17 #
18 # == Usage
19 # To be able to use these helpers, you must first include the Prototype
20 # JavaScript framework in your pages.
21 #
22 # javascript_include_tag 'prototype'
23 #
24 # (See the documentation for
25 # ActionView::Helpers::JavaScriptHelper for more information on including
26 # this and other JavaScript files in your Rails templates.)
27 #
28 # Now you're ready to call a remote action either through a link...
29 #
30 # link_to_remote "Add to cart",
31 # :url => { :action => "add", :id => product.id },
32 # :update => { :success => "cart", :failure => "error" }
33 #
34 # ...through a form...
35 #
36 # <% form_remote_tag :url => '/shipping' do -%>
37 # <div><%= submit_tag 'Recalculate Shipping' %></div>
38 # <% end -%>
39 #
40 # ...periodically...
41 #
42 # periodically_call_remote(:url => 'update', :frequency => '5', :update => 'ticker')
43 #
44 # ...or through an observer (i.e., a form or field that is observed and calls a remote
45 # action when changed).
46 #
47 # <%= observe_field(:searchbox,
48 # :url => { :action => :live_search }),
49 # :frequency => 0.5,
50 # :update => :hits,
51 # :with => 'query'
52 # %>
53 #
54 # As you can see, there are numerous ways to use Prototype's Ajax functions (and actually more than
55 # are listed here); check out the documentation for each method to find out more about its usage and options.
56 #
57 # === Common Options
58 # See link_to_remote for documentation of options common to all Ajax
59 # helpers; any of the options specified by link_to_remote can be used
60 # by the other helpers.
61 #
62 # == Designing your Rails actions for Ajax
63 # When building your action handlers (that is, the Rails actions that receive your background requests), it's
64 # important to remember a few things. First, whatever your action would normally return to the browser, it will
65 # return to the Ajax call. As such, you typically don't want to render with a layout. This call will cause
66 # 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.
67 # You can turn the layout off on particular actions by doing the following:
68 #
69 # class SiteController < ActionController::Base
70 # layout "standard", :except => [:ajax_method, :more_ajax, :another_ajax]
71 # end
72 #
73 # Optionally, you could do this in the method you wish to lack a layout:
74 #
75 # render :layout => false
76 #
77 # You can tell the type of request from within your action using the <tt>request.xhr?</tt> (XmlHttpRequest, the
78 # method that Ajax uses to make background requests) method.
79 # def name
80 # # Is this an XmlHttpRequest request?
81 # if (request.xhr?)
82 # render :text => @name.to_s
83 # else
84 # # No? Then render an action.
85 # render :action => 'view_attribute', :attr => @name
86 # end
87 # end
88 #
89 # The else clause can be left off and the current action will render with full layout and template. An extension
90 # to this solution was posted to Ryan Heneise's blog at ArtOfMission["http://www.artofmission.com/"].
91 #
92 # layout proc{ |c| c.request.xhr? ? false : "application" }
93 #
94 # Dropping this in your ApplicationController turns the layout off for every request that is an "xhr" request.
95 #
96 # If you are just returning a little data or don't want to build a template for your output, you may opt to simply
97 # render text output, like this:
98 #
99 # render :text => 'Return this from my method!'
100 #
101 # Since whatever the method returns is injected into the DOM, this will simply inject some text (or HTML, if you
102 # tell it to). This is usually how small updates, such updating a cart total or a file count, are handled.
103 #
104 # == Updating multiple elements
105 # See JavaScriptGenerator for information on updating multiple elements
106 # on the page in an Ajax response.
107 module PrototypeHelper
108 unless const_defined? :CALLBACKS
109 CALLBACKS = Set.new([ :uninitialized, :loading, :loaded,
110 :interactive, :complete, :failure, :success ] +
111 (100..599).to_a)
112 AJAX_OPTIONS = Set.new([ :before, :after, :condition, :url,
113 :asynchronous, :method, :insertion, :position,
114 :form, :with, :update, :script, :type ]).merge(CALLBACKS)
115 end
116
117 # Returns a link to a remote action defined by <tt>options[:url]</tt>
118 # (using the url_for format) that's called in the background using
119 # XMLHttpRequest. The result of that request can then be inserted into a
120 # DOM object whose id can be specified with <tt>options[:update]</tt>.
121 # Usually, the result would be a partial prepared by the controller with
122 # render :partial.
123 #
124 # Examples:
125 # # Generates: <a href="#" onclick="new Ajax.Updater('posts', '/blog/destroy/3', {asynchronous:true, evalScripts:true});
126 # # return false;">Delete this post</a>
127 # link_to_remote "Delete this post", :update => "posts",
128 # :url => { :action => "destroy", :id => post.id }
129 #
130 # # Generates: <a href="#" onclick="new Ajax.Updater('emails', '/mail/list_emails', {asynchronous:true, evalScripts:true});
131 # # return false;"><img alt="Refresh" src="/images/refresh.png?" /></a>
132 # link_to_remote(image_tag("refresh"), :update => "emails",
133 # :url => { :action => "list_emails" })
134 #
135 # You can override the generated HTML options by specifying a hash in
136 # <tt>options[:html]</tt>.
137 #
138 # link_to_remote "Delete this post", :update => "posts",
139 # :url => post_url(@post), :method => :delete,
140 # :html => { :class => "destructive" }
141 #
142 # You can also specify a hash for <tt>options[:update]</tt> to allow for
143 # easy redirection of output to an other DOM element if a server-side
144 # error occurs:
145 #
146 # Example:
147 # # Generates: <a href="#" onclick="new Ajax.Updater({success:'posts',failure:'error'}, '/blog/destroy/5',
148 # # {asynchronous:true, evalScripts:true}); return false;">Delete this post</a>
149 # link_to_remote "Delete this post",
150 # :url => { :action => "destroy", :id => post.id },
151 # :update => { :success => "posts", :failure => "error" }
152 #
153 # Optionally, you can use the <tt>options[:position]</tt> parameter to
154 # influence how the target DOM element is updated. It must be one of
155 # <tt>:before</tt>, <tt>:top</tt>, <tt>:bottom</tt>, or <tt>:after</tt>.
156 #
157 # The method used is by default POST. You can also specify GET or you
158 # can simulate PUT or DELETE over POST. All specified with <tt>options[:method]</tt>
159 #
160 # Example:
161 # # Generates: <a href="#" onclick="new Ajax.Request('/person/4', {asynchronous:true, evalScripts:true, method:'delete'});
162 # # return false;">Destroy</a>
163 # link_to_remote "Destroy", :url => person_url(:id => person), :method => :delete
164 #
165 # By default, these remote requests are processed asynchronous during
166 # which various JavaScript callbacks can be triggered (for progress
167 # indicators and the likes). All callbacks get access to the
168 # <tt>request</tt> object, which holds the underlying XMLHttpRequest.
169 #
170 # To access the server response, use <tt>request.responseText</tt>, to
171 # find out the HTTP status, use <tt>request.status</tt>.
172 #
173 # Example:
174 # # Generates: <a href="#" onclick="new Ajax.Request('/words/undo?n=33', {asynchronous:true, evalScripts:true,
175 # # onComplete:function(request){undoRequestCompleted(request)}}); return false;">hello</a>
176 # word = 'hello'
177 # link_to_remote word,
178 # :url => { :action => "undo", :n => word_counter },
179 # :complete => "undoRequestCompleted(request)"
180 #
181 # The callbacks that may be specified are (in order):
182 #
183 # <tt>:loading</tt>:: Called when the remote document is being
184 # loaded with data by the browser.
185 # <tt>:loaded</tt>:: Called when the browser has finished loading
186 # the remote document.
187 # <tt>:interactive</tt>:: Called when the user can interact with the
188 # remote document, even though it has not
189 # finished loading.
190 # <tt>:success</tt>:: Called when the XMLHttpRequest is completed,
191 # and the HTTP status code is in the 2XX range.
192 # <tt>:failure</tt>:: Called when the XMLHttpRequest is completed,
193 # and the HTTP status code is not in the 2XX
194 # range.
195 # <tt>:complete</tt>:: Called when the XMLHttpRequest is complete
196 # (fires after success/failure if they are
197 # present).
198 #
199 # You can further refine <tt>:success</tt> and <tt>:failure</tt> by
200 # adding additional callbacks for specific status codes.
201 #
202 # Example:
203 # # Generates: <a href="#" onclick="new Ajax.Request('/testing/action', {asynchronous:true, evalScripts:true,
204 # # on404:function(request){alert('Not found...? Wrong URL...?')},
205 # # onFailure:function(request){alert('HTTP Error ' + request.status + '!')}}); return false;">hello</a>
206 # link_to_remote word,
207 # :url => { :action => "action" },
208 # 404 => "alert('Not found...? Wrong URL...?')",
209 # :failure => "alert('HTTP Error ' + request.status + '!')"
210 #
211 # A status code callback overrides the success/failure handlers if
212 # present.
213 #
214 # If you for some reason or another need synchronous processing (that'll
215 # block the browser while the request is happening), you can specify
216 # <tt>options[:type] = :synchronous</tt>.
217 #
218 # You can customize further browser side call logic by passing in
219 # JavaScript code snippets via some optional parameters. In their order
220 # of use these are:
221 #
222 # <tt>:confirm</tt>:: Adds confirmation dialog.
223 # <tt>:condition</tt>:: Perform remote request conditionally
224 # by this expression. Use this to
225 # describe browser-side conditions when
226 # request should not be initiated.
227 # <tt>:before</tt>:: Called before request is initiated.
228 # <tt>:after</tt>:: Called immediately after request was
229 # initiated and before <tt>:loading</tt>.
230 # <tt>:submit</tt>:: Specifies the DOM element ID that's used
231 # as the parent of the form elements. By
232 # default this is the current form, but
233 # it could just as well be the ID of a
234 # table row or any other DOM element.
235 # <tt>:with</tt>:: A JavaScript expression specifying
236 # the parameters for the XMLHttpRequest.
237 # Any expressions should return a valid
238 # URL query string.
239 #
240 # Example:
241 #
242 # :with => "'name=' + $('name').value"
243 #
244 # You can generate a link that uses AJAX in the general case, while
245 # degrading gracefully to plain link behavior in the absence of
246 # JavaScript by setting <tt>html_options[:href]</tt> to an alternate URL.
247 # Note the extra curly braces around the <tt>options</tt> hash separate
248 # it as the second parameter from <tt>html_options</tt>, the third.
249 #
250 # Example:
251 # link_to_remote "Delete this post",
252 # { :update => "posts", :url => { :action => "destroy", :id => post.id } },
253 # :href => url_for(:action => "destroy", :id => post.id)
254 def link_to_remote(name, options = {}, html_options = nil)
255 link_to_function(name, remote_function(options), html_options || options.delete(:html))
256 end
257
258 # Creates a button with an onclick event which calls a remote action
259 # via XMLHttpRequest
260 # The options for specifying the target with :url
261 # and defining callbacks is the same as link_to_remote.
262 def button_to_remote(name, options = {}, html_options = {})
263 button_to_function(name, remote_function(options), html_options)
264 end
265
266 # Periodically calls the specified url (<tt>options[:url]</tt>) every
267 # <tt>options[:frequency]</tt> seconds (default is 10). Usually used to
268 # update a specified div (<tt>options[:update]</tt>) with the results
269 # of the remote call. The options for specifying the target with <tt>:url</tt>
270 # and defining callbacks is the same as link_to_remote.
271 # Examples:
272 # # Call get_averages and put its results in 'avg' every 10 seconds
273 # # Generates:
274 # # new PeriodicalExecuter(function() {new Ajax.Updater('avg', '/grades/get_averages',
275 # # {asynchronous:true, evalScripts:true})}, 10)
276 # periodically_call_remote(:url => { :action => 'get_averages' }, :update => 'avg')
277 #
278 # # Call invoice every 10 seconds with the id of the customer
279 # # If it succeeds, update the invoice DIV; if it fails, update the error DIV
280 # # Generates:
281 # # new PeriodicalExecuter(function() {new Ajax.Updater({success:'invoice',failure:'error'},
282 # # '/testing/invoice/16', {asynchronous:true, evalScripts:true})}, 10)
283 # periodically_call_remote(:url => { :action => 'invoice', :id => customer.id },
284 # :update => { :success => "invoice", :failure => "error" }
285 #
286 # # Call update every 20 seconds and update the new_block DIV
287 # # Generates:
288 # # new PeriodicalExecuter(function() {new Ajax.Updater('news_block', 'update', {asynchronous:true, evalScripts:true})}, 20)
289 # periodically_call_remote(:url => 'update', :frequency => '20', :update => 'news_block')
290 #
291 def periodically_call_remote(options = {})
292 frequency = options[:frequency] || 10 # every ten seconds by default
293 code = "new PeriodicalExecuter(function() {#{remote_function(options)}}, #{frequency})"
294 javascript_tag(code)
295 end
296
297 # Returns a form tag that will submit using XMLHttpRequest in the
298 # background instead of the regular reloading POST arrangement. Even
299 # though it's using JavaScript to serialize the form elements, the form
300 # submission will work just like a regular submission as viewed by the
301 # receiving side (all elements available in <tt>params</tt>). The options for
302 # specifying the target with <tt>:url</tt> and defining callbacks is the same as
303 # +link_to_remote+.
304 #
305 # A "fall-through" target for browsers that doesn't do JavaScript can be
306 # specified with the <tt>:action</tt>/<tt>:method</tt> options on <tt>:html</tt>.
307 #
308 # Example:
309 # # Generates:
310 # # <form action="/some/place" method="post" onsubmit="new Ajax.Request('',
311 # # {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;">
312 # form_remote_tag :html => { :action =>
313 # url_for(:controller => "some", :action => "place") }
314 #
315 # The Hash passed to the <tt>:html</tt> key is equivalent to the options (2nd)
316 # argument in the FormTagHelper.form_tag method.
317 #
318 # By default the fall-through action is the same as the one specified in
319 # the <tt>:url</tt> (and the default method is <tt>:post</tt>).
320 #
321 # form_remote_tag also takes a block, like form_tag:
322 # # Generates:
323 # # <form action="/" method="post" onsubmit="new Ajax.Request('/',
324 # # {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)});
325 # # return false;"> <div><input name="commit" type="submit" value="Save" /></div>
326 # # </form>
327 # <% form_remote_tag :url => '/posts' do -%>
328 # <div><%= submit_tag 'Save' %></div>
329 # <% end -%>
330 def form_remote_tag(options = {}, &block)
331 options[:form] = true
332
333 options[:html] ||= {}
334 options[:html][:onsubmit] =
335 (options[:html][:onsubmit] ? options[:html][:onsubmit] + "; " : "") +
336 "#{remote_function(options)}; return false;"
337
338 form_tag(options[:html].delete(:action) || url_for(options[:url]), options[:html], &block)
339 end
340
341 # Creates a form that will submit using XMLHttpRequest in the background
342 # instead of the regular reloading POST arrangement and a scope around a
343 # specific resource that is used as a base for questioning about
344 # values for the fields.
345 #
346 # === Resource
347 #
348 # Example:
349 # <% remote_form_for(@post) do |f| %>
350 # ...
351 # <% end %>
352 #
353 # This will expand to be the same as:
354 #
355 # <% remote_form_for :post, @post, :url => post_path(@post), :html => { :method => :put, :class => "edit_post", :id => "edit_post_45" } do |f| %>
356 # ...
357 # <% end %>
358 #
359 # === Nested Resource
360 #
361 # Example:
362 # <% remote_form_for([@post, @comment]) do |f| %>
363 # ...
364 # <% end %>
365 #
366 # This will expand to be the same as:
367 #
368 # <% remote_form_for :comment, @comment, :url => post_comment_path(@post, @comment), :html => { :method => :put, :class => "edit_comment", :id => "edit_comment_45" } do |f| %>
369 # ...
370 # <% end %>
371 #
372 # If you don't need to attach a form to a resource, then check out form_remote_tag.
373 #
374 # See FormHelper#form_for for additional semantics.
375 def remote_form_for(record_or_name_or_array, *args, &proc)
376 options = args.extract_options!
377
378 case record_or_name_or_array
379 when String, Symbol
380 object_name = record_or_name_or_array
381 when Array
382 object = record_or_name_or_array.last
383 object_name = ActionController::RecordIdentifier.singular_class_name(object)
384 apply_form_for_options!(record_or_name_or_array, options)
385 args.unshift object
386 else
387 object = record_or_name_or_array
388 object_name = ActionController::RecordIdentifier.singular_class_name(record_or_name_or_array)
389 apply_form_for_options!(object, options)
390 args.unshift object
391 end
392
393 concat(form_remote_tag(options))
394 fields_for(object_name, *(args << options), &proc)
395 concat('</form>')
396 end
397 alias_method :form_remote_for, :remote_form_for
398
399 # Returns a button input tag with the element name of +name+ and a value (i.e., display text) of +value+
400 # that will submit form using XMLHttpRequest in the background instead of a regular POST request that
401 # reloads the page.
402 #
403 # # Create a button that submits to the create action
404 # #
405 # # Generates: <input name="create_btn" onclick="new Ajax.Request('/testing/create',
406 # # {asynchronous:true, evalScripts:true, parameters:Form.serialize(this.form)});
407 # # return false;" type="button" value="Create" />
408 # <%= submit_to_remote 'create_btn', 'Create', :url => { :action => 'create' } %>
409 #
410 # # Submit to the remote action update and update the DIV succeed or fail based
411 # # on the success or failure of the request
412 # #
413 # # Generates: <input name="update_btn" onclick="new Ajax.Updater({success:'succeed',failure:'fail'},
414 # # '/testing/update', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this.form)});
415 # # return false;" type="button" value="Update" />
416 # <%= submit_to_remote 'update_btn', 'Update', :url => { :action => 'update' },
417 # :update => { :success => "succeed", :failure => "fail" }
418 #
419 # <tt>options</tt> argument is the same as in form_remote_tag.
420 def submit_to_remote(name, value, options = {})
421 options[:with] ||= 'Form.serialize(this.form)'
422
423 html_options = options.delete(:html) || {}
424 html_options[:name] = name
425
426 button_to_remote(value, options, html_options)
427 end
428
429 # Returns '<tt>eval(request.responseText)</tt>' which is the JavaScript function
430 # that +form_remote_tag+ can call in <tt>:complete</tt> to evaluate a multiple
431 # update return document using +update_element_function+ calls.
432 def evaluate_remote_response
433 "eval(request.responseText)"
434 end
435
436 # Returns the JavaScript needed for a remote function.
437 # Takes the same arguments as link_to_remote.
438 #
439 # Example:
440 # # Generates: <select id="options" onchange="new Ajax.Updater('options',
441 # # '/testing/update_options', {asynchronous:true, evalScripts:true})">
442 # <select id="options" onchange="<%= remote_function(:update => "options",
443 # :url => { :action => :update_options }) %>">
444 # <option value="0">Hello</option>
445 # <option value="1">World</option>
446 # </select>
447 def remote_function(options)
448 javascript_options = options_for_ajax(options)
449
450 update = ''
451 if options[:update] && options[:update].is_a?(Hash)
452 update = []
453 update << "success:'#{options[:update][:success]}'" if options[:update][:success]
454 update << "failure:'#{options[:update][:failure]}'" if options[:update][:failure]
455 update = '{' + update.join(',') + '}'
456 elsif options[:update]
457 update << "'#{options[:update]}'"
458 end
459
460 function = update.empty? ?
461 "new Ajax.Request(" :
462 "new Ajax.Updater(#{update}, "
463
464 url_options = options[:url]
465 url_options = url_options.merge(:escape => false) if url_options.is_a?(Hash)
466 function << "'#{escape_javascript(url_for(url_options))}'"
467 function << ", #{javascript_options})"
468
469 function = "#{options[:before]}; #{function}" if options[:before]
470 function = "#{function}; #{options[:after]}" if options[:after]
471 function = "if (#{options[:condition]}) { #{function}; }" if options[:condition]
472 function = "if (confirm('#{escape_javascript(options[:confirm])}')) { #{function}; }" if options[:confirm]
473
474 return function
475 end
476
477 # Observes the field with the DOM ID specified by +field_id+ and calls a
478 # callback when its contents have changed. The default callback is an
479 # Ajax call. By default the value of the observed field is sent as a
480 # parameter with the Ajax call.
481 #
482 # Example:
483 # # Generates: new Form.Element.Observer('suggest', 0.25, function(element, value) {new Ajax.Updater('suggest',
484 # # '/testing/find_suggestion', {asynchronous:true, evalScripts:true, parameters:'q=' + value})})
485 # <%= observe_field :suggest, :url => { :action => :find_suggestion },
486 # :frequency => 0.25,
487 # :update => :suggest,
488 # :with => 'q'
489 # %>
490 #
491 # Required +options+ are either of:
492 # <tt>:url</tt>:: +url_for+-style options for the action to call
493 # when the field has changed.
494 # <tt>:function</tt>:: Instead of making a remote call to a URL, you
495 # can specify javascript code to be called instead.
496 # Note that the value of this option is used as the
497 # *body* of the javascript function, a function definition
498 # with parameters named element and value will be generated for you
499 # for example:
500 # observe_field("glass", :frequency => 1, :function => "alert('Element changed')")
501 # will generate:
502 # new Form.Element.Observer('glass', 1, function(element, value) {alert('Element changed')})
503 # The element parameter is the DOM element being observed, and the value is its value at the
504 # time the observer is triggered.
505 #
506 # Additional options are:
507 # <tt>:frequency</tt>:: The frequency (in seconds) at which changes to
508 # this field will be detected. Not setting this
509 # option at all or to a value equal to or less than
510 # zero will use event based observation instead of
511 # time based observation.
512 # <tt>:update</tt>:: Specifies the DOM ID of the element whose
513 # innerHTML should be updated with the
514 # XMLHttpRequest response text.
515 # <tt>:with</tt>:: A JavaScript expression specifying the parameters
516 # for the XMLHttpRequest. The default is to send the
517 # key and value of the observed field. Any custom
518 # expressions should return a valid URL query string.
519 # The value of the field is stored in the JavaScript
520 # variable +value+.
521 #
522 # Examples
523 #
524 # :with => "'my_custom_key=' + value"
525 # :with => "'person[name]=' + prompt('New name')"
526 # :with => "Form.Element.serialize('other-field')"
527 #
528 # Finally
529 # :with => 'name'
530 # is shorthand for
531 # :with => "'name=' + value"
532 # This essentially just changes the key of the parameter.
533 # <tt>:on</tt>:: Specifies which event handler to observe. By default,
534 # it's set to "changed" for text fields and areas and
535 # "click" for radio buttons and checkboxes. With this,
536 # you can specify it instead to be "blur" or "focus" or
537 # any other event.
538 #
539 # Additionally, you may specify any of the options documented in the
540 # <em>Common options</em> section at the top of this document.
541 #
542 # Example:
543 #
544 # # Sends params: {:title => 'Title of the book'} when the book_title input
545 # # field is changed.
546 # observe_field 'book_title',
547 # :url => 'http://example.com/books/edit/1',
548 # :with => 'title'
549 #
550 # # Sends params: {:book_title => 'Title of the book'} when the focus leaves
551 # # the input field.
552 # observe_field 'book_title',
553 # :url => 'http://example.com/books/edit/1',
554 # :on => 'blur'
555 #
556 def observe_field(field_id, options = {})
557 if options[:frequency] && options[:frequency] > 0
558 build_observer('Form.Element.Observer', field_id, options)
559 else
560 build_observer('Form.Element.EventObserver', field_id, options)
561 end
562 end
563
564 # Observes the form with the DOM ID specified by +form_id+ and calls a
565 # callback when its contents have changed. The default callback is an
566 # Ajax call. By default all fields of the observed field are sent as
567 # parameters with the Ajax call.
568 #
569 # The +options+ for +observe_form+ are the same as the options for
570 # +observe_field+. The JavaScript variable +value+ available to the
571 # <tt>:with</tt> option is set to the serialized form by default.
572 def observe_form(form_id, options = {})
573 if options[:frequency]
574 build_observer('Form.Observer', form_id, options)
575 else
576 build_observer('Form.EventObserver', form_id, options)
577 end
578 end
579
580 # All the methods were moved to GeneratorMethods so that
581 # #include_helpers_from_context has nothing to overwrite.
582 class JavaScriptGenerator #:nodoc:
583 def initialize(context, &block) #:nodoc:
584 @context, @lines = context, []
585 include_helpers_from_context
586 @context.with_output_buffer(@lines) do
587 @context.instance_exec(self, &block)
588 end
589 end
590
591 private
592 def include_helpers_from_context
593 extend @context.helpers if @context.respond_to?(:helpers)
594 extend GeneratorMethods
595 end
596
597 # JavaScriptGenerator generates blocks of JavaScript code that allow you
598 # to change the content and presentation of multiple DOM elements. Use
599 # this in your Ajax response bodies, either in a <script> tag or as plain
600 # JavaScript sent with a Content-type of "text/javascript".
601 #
602 # Create new instances with PrototypeHelper#update_page or with
603 # ActionController::Base#render, then call +insert_html+, +replace_html+,
604 # +remove+, +show+, +hide+, +visual_effect+, or any other of the built-in
605 # methods on the yielded generator in any order you like to modify the
606 # content and appearance of the current page.
607 #
608 # Example:
609 #
610 # # Generates:
611 # # new Element.insert("list", { bottom: "<li>Some item</li>" });
612 # # new Effect.Highlight("list");
613 # # ["status-indicator", "cancel-link"].each(Element.hide);
614 # update_page do |page|
615 # page.insert_html :bottom, 'list', "<li>#{@item.name}</li>"
616 # page.visual_effect :highlight, 'list'
617 # page.hide 'status-indicator', 'cancel-link'
618 # end
619 #
620 #
621 # Helper methods can be used in conjunction with JavaScriptGenerator.
622 # When a helper method is called inside an update block on the +page+
623 # object, that method will also have access to a +page+ object.
624 #
625 # Example:
626 #
627 # module ApplicationHelper
628 # def update_time
629 # page.replace_html 'time', Time.now.to_s(:db)
630 # page.visual_effect :highlight, 'time'
631 # end
632 # end
633 #
634 # # Controller action
635 # def poll
636 # render(:update) { |page| page.update_time }
637 # end
638 #
639 # Calls to JavaScriptGenerator not matching a helper method below
640 # generate a proxy to the JavaScript Class named by the method called.
641 #
642 # Examples:
643 #
644 # # Generates:
645 # # Foo.init();
646 # update_page do |page|
647 # page.foo.init
648 # end
649 #
650 # # Generates:
651 # # Event.observe('one', 'click', function () {
652 # # $('two').show();
653 # # });
654 # update_page do |page|
655 # page.event.observe('one', 'click') do |p|
656 # p[:two].show
657 # end
658 # end
659 #
660 # You can also use PrototypeHelper#update_page_tag instead of
661 # PrototypeHelper#update_page to wrap the generated JavaScript in a
662 # <script> tag.
663 module GeneratorMethods
664 def to_s #:nodoc:
665 returning javascript = @lines * $/ do
666 if ActionView::Base.debug_rjs
667 source = javascript.dup
668 javascript.replace "try {\n#{source}\n} catch (e) "
669 javascript << "{ alert('RJS error:\\n\\n' + e.toString()); alert('#{source.gsub('\\','\0\0').gsub(/\r\n|\n|\r/, "\\n").gsub(/["']/) { |m| "\\#{m}" }}'); throw e }"
670 end
671 end
672 end
673
674 # Returns a element reference by finding it through +id+ in the DOM. This element can then be
675 # used for further method calls. Examples:
676 #
677 # page['blank_slate'] # => $('blank_slate');
678 # page['blank_slate'].show # => $('blank_slate').show();
679 # page['blank_slate'].show('first').up # => $('blank_slate').show('first').up();
680 #
681 # You can also pass in a record, which will use ActionController::RecordIdentifier.dom_id to lookup
682 # the correct id:
683 #
684 # page[@post] # => $('post_45')
685 # page[Post.new] # => $('new_post')
686 def [](id)
687 case id
688 when String, Symbol, NilClass
689 JavaScriptElementProxy.new(self, id)
690 else
691 JavaScriptElementProxy.new(self, ActionController::RecordIdentifier.dom_id(id))
692 end
693 end
694
695 # Returns an object whose <tt>to_json</tt> evaluates to +code+. Use this to pass a literal JavaScript
696 # expression as an argument to another JavaScriptGenerator method.
697 def literal(code)
698 ActiveSupport::JSON::Variable.new(code.to_s)
699 end
700
701 # Returns a collection reference by finding it through a CSS +pattern+ in the DOM. This collection can then be
702 # used for further method calls. Examples:
703 #
704 # page.select('p') # => $$('p');
705 # page.select('p.welcome b').first # => $$('p.welcome b').first();
706 # page.select('p.welcome b').first.hide # => $$('p.welcome b').first().hide();
707 #
708 # You can also use prototype enumerations with the collection. Observe:
709 #
710 # # Generates: $$('#items li').each(function(value) { value.hide(); });
711 # page.select('#items li').each do |value|
712 # value.hide
713 # end
714 #
715 # Though you can call the block param anything you want, they are always rendered in the
716 # javascript as 'value, index.' Other enumerations, like collect() return the last statement:
717 #
718 # # Generates: var hidden = $$('#items li').collect(function(value, index) { return value.hide(); });
719 # page.select('#items li').collect('hidden') do |item|
720 # item.hide
721 # end
722 #
723 def select(pattern)
724 JavaScriptElementCollectionProxy.new(self, pattern)
725 end
726
727 # Inserts HTML at the specified +position+ relative to the DOM element
728 # identified by the given +id+.
729 #
730 # +position+ may be one of:
731 #
732 # <tt>:top</tt>:: HTML is inserted inside the element, before the
733 # element's existing content.
734 # <tt>:bottom</tt>:: HTML is inserted inside the element, after the
735 # element's existing content.
736 # <tt>:before</tt>:: HTML is inserted immediately preceding the element.
737 # <tt>:after</tt>:: HTML is inserted immediately following the element.
738 #
739 # +options_for_render+ may be either a string of HTML to insert, or a hash
740 # of options to be passed to ActionView::Base#render. For example:
741 #
742 # # Insert the rendered 'navigation' partial just before the DOM
743 # # element with ID 'content'.
744 # # Generates: Element.insert("content", { before: "-- Contents of 'navigation' partial --" });
745 # page.insert_html :before, 'content', :partial => 'navigation'
746 #
747 # # Add a list item to the bottom of the <ul> with ID 'list'.
748 # # Generates: Element.insert("list", { bottom: "<li>Last item</li>" });
749 # page.insert_html :bottom, 'list', '<li>Last item</li>'
750 #
751 def insert_html(position, id, *options_for_render)
752 content = javascript_object_for(render(*options_for_render))
753 record "Element.insert(\"#{id}\", { #{position.to_s.downcase}: #{content} });"
754 end
755
756 # Replaces the inner HTML of the DOM element with the given +id+.
757 #
758 # +options_for_render+ may be either a string of HTML to insert, or a hash
759 # of options to be passed to ActionView::Base#render. For example:
760 #
761 # # Replace the HTML of the DOM element having ID 'person-45' with the
762 # # 'person' partial for the appropriate object.
763 # # Generates: Element.update("person-45", "-- Contents of 'person' partial --");
764 # page.replace_html 'person-45', :partial => 'person', :object => @person
765 #
766 def replace_html(id, *options_for_render)
767 call 'Element.update', id, render(*options_for_render)
768 end
769
770 # Replaces the "outer HTML" (i.e., the entire element, not just its
771 # contents) of the DOM element with the given +id+.
772 #
773 # +options_for_render+ may be either a string of HTML to insert, or a hash
774 # of options to be passed to ActionView::Base#render. For example:
775 #
776 # # Replace the DOM element having ID 'person-45' with the
777 # # 'person' partial for the appropriate object.
778 # page.replace 'person-45', :partial => 'person', :object => @person
779 #
780 # This allows the same partial that is used for the +insert_html+ to
781 # be also used for the input to +replace+ without resorting to
782 # the use of wrapper elements.
783 #
784 # Examples:
785 #
786 # <div id="people">
787 # <%= render :partial => 'person', :collection => @people %>
788 # </div>
789 #
790 # # Insert a new person
791 # #
792 # # Generates: new Insertion.Bottom({object: "Matz", partial: "person"}, "");
793 # page.insert_html :bottom, :partial => 'person', :object => @person
794 #
795 # # Replace an existing person
796 #
797 # # Generates: Element.replace("person_45", "-- Contents of partial --");
798 # page.replace 'person_45', :partial => 'person', :object => @person
799 #
800 def replace(id, *options_for_render)
801 call 'Element.replace', id, render(*options_for_render)
802 end
803
804 # Removes the DOM elements with the given +ids+ from the page.
805 #
806 # Example:
807 #
808 # # Remove a few people
809 # # Generates: ["person_23", "person_9", "person_2"].each(Element.remove);
810 # page.remove 'person_23', 'person_9', 'person_2'
811 #
812 def remove(*ids)
813 loop_on_multiple_args 'Element.remove', ids
814 end
815
816 # Shows hidden DOM elements with the given +ids+.
817 #
818 # Example:
819 #
820 # # Show a few people
821 # # Generates: ["person_6", "person_13", "person_223"].each(Element.show);
822 # page.show 'person_6', 'person_13', 'person_223'
823 #
824 def show(*ids)
825 loop_on_multiple_args 'Element.show', ids
826 end
827
828 # Hides the visible DOM elements with the given +ids+.
829 #
830 # Example:
831 #
832 # # Hide a few people
833 # # Generates: ["person_29", "person_9", "person_0"].each(Element.hide);
834 # page.hide 'person_29', 'person_9', 'person_0'
835 #
836 def hide(*ids)
837 loop_on_multiple_args 'Element.hide', ids
838 end
839
840 # Toggles the visibility of the DOM elements with the given +ids+.
841 # Example:
842 #
843 # # Show a few people
844 # # Generates: ["person_14", "person_12", "person_23"].each(Element.toggle);
845 # page.toggle 'person_14', 'person_12', 'person_23' # Hides the elements
846 # page.toggle 'person_14', 'person_12', 'person_23' # Shows the previously hidden elements
847 #
848 def toggle(*ids)
849 loop_on_multiple_args 'Element.toggle', ids
850 end
851
852 # Displays an alert dialog with the given +message+.
853 #
854 # Example:
855 #
856 # # Generates: alert('This message is from Rails!')
857 # page.alert('This message is from Rails!')
858 def alert(message)
859 call 'alert', message
860 end
861
862 # Redirects the browser to the given +location+ using JavaScript, in the same form as +url_for+.
863 #
864 # Examples:
865 #
866 # # Generates: window.location.href = "/mycontroller";
867 # page.redirect_to(:action => 'index')
868 #
869 # # Generates: window.location.href = "/account/signup";
870 # page.redirect_to(:controller => 'account', :action => 'signup')
871 def redirect_to(location)
872 url = location.is_a?(String) ? location : @context.url_for(location)
873 record "window.location.href = #{url.inspect}"
874 end
875
876 # Reloads the browser's current +location+ using JavaScript
877 #
878 # Examples:
879 #
880 # # Generates: window.location.reload();
881 # page.reload
882 def reload
883 record 'window.location.reload()'
884 end
885
886 # Calls the JavaScript +function+, optionally with the given +arguments+.
887 #
888 # If a block is given, the block will be passed to a new JavaScriptGenerator;
889 # the resulting JavaScript code will then be wrapped inside <tt>function() { ... }</tt>
890 # and passed as the called function's final argument.
891 #
892 # Examples:
893 #
894 # # Generates: Element.replace(my_element, "My content to replace with.")
895 # page.call 'Element.replace', 'my_element', "My content to replace with."
896 #
897 # # Generates: alert('My message!')
898 # page.call 'alert', 'My message!'
899 #
900 # # Generates:
901 # # my_method(function() {
902 # # $("one").show();
903 # # $("two").hide();
904 # # });
905 # page.call(:my_method) do |p|
906 # p[:one].show
907 # p[:two].hide
908 # end
909 def call(function, *arguments, &block)
910 record "#{function}(#{arguments_for_call(arguments, block)})"
911 end
912
913 # Assigns the JavaScript +variable+ the given +value+.
914 #
915 # Examples:
916 #
917 # # Generates: my_string = "This is mine!";
918 # page.assign 'my_string', 'This is mine!'
919 #
920 # # Generates: record_count = 33;
921 # page.assign 'record_count', 33
922 #
923 # # Generates: tabulated_total = 47
924 # page.assign 'tabulated_total', @total_from_cart
925 #
926 def assign(variable, value)
927 record "#{variable} = #{javascript_object_for(value)}"
928 end
929
930 # Writes raw JavaScript to the page.
931 #
932 # Example:
933 #
934 # page << "alert('JavaScript with Prototype.');"
935 def <<(javascript)
936 @lines << javascript
937 end
938
939 # Executes the content of the block after a delay of +seconds+. Example:
940 #
941 # # Generates:
942 # # setTimeout(function() {
943 # # ;
944 # # new Effect.Fade("notice",{});
945 # # }, 20000);
946 # page.delay(20) do
947 # page.visual_effect :fade, 'notice'
948 # end
949 def delay(seconds = 1)
950 record "setTimeout(function() {\n\n"
951 yield
952 record "}, #{(seconds * 1000).to_i})"
953 end
954
955 # Starts a script.aculo.us visual effect. See
956 # ActionView::Helpers::ScriptaculousHelper for more information.
957 def visual_effect(name, id = nil, options = {})
958 record @context.send(:visual_effect, name, id, options)
959 end
960
961 # Creates a script.aculo.us sortable element. Useful
962 # to recreate sortable elements after items get added
963 # or deleted.
964 # See ActionView::Helpers::ScriptaculousHelper for more information.
965 def sortable(id, options = {})
966 record @context.send(:sortable_element_js, id, options)
967 end
968
969 # Creates a script.aculo.us draggable element.
970 # See ActionView::Helpers::ScriptaculousHelper for more information.
971 def draggable(id, options = {})
972 record @context.send(:draggable_element_js, id, options)
973 end
974
975 # Creates a script.aculo.us drop receiving element.
976 # See ActionView::Helpers::ScriptaculousHelper for more information.
977 def drop_receiving(id, options = {})
978 record @context.send(:drop_receiving_element_js, id, options)
979 end
980
981 private
982 def loop_on_multiple_args(method, ids)
983 record(ids.size>1 ?
984 "#{javascript_object_for(ids)}.each(#{method})" :
985 "#{method}(#{ids.first.to_json})")
986 end
987
988 def page
989 self
990 end
991
992 def record(line)
993 returning line = "#{line.to_s.chomp.gsub(/\;\z/, '')};" do
994 self << line
995 end
996 end
997
998 def render(*options_for_render)
999 old_format = @context && @context.template_format
1000 @context.template_format = :html if @context
1001 Hash === options_for_render.first ?
1002 @context.render(*options_for_render) :
1003 options_for_render.first.to_s
1004 ensure
1005 @context.template_format = old_format if @context
1006 end
1007
1008 def javascript_object_for(object)
1009 object.respond_to?(:to_json) ? object.to_json : object.inspect
1010 end
1011
1012 def arguments_for_call(arguments, block = nil)
1013 arguments << block_to_function(block) if block
1014 arguments.map { |argument| javascript_object_for(argument) }.join ', '
1015 end
1016
1017 def block_to_function(block)
1018 generator = self.class.new(@context, &block)
1019 literal("function() { #{generator.to_s} }")
1020 end
1021
1022 def method_missing(method, *arguments)
1023 JavaScriptProxy.new(self, method.to_s.camelize)
1024 end
1025 end
1026 end
1027
1028 # Yields a JavaScriptGenerator and returns the generated JavaScript code.
1029 # Use this to update multiple elements on a page in an Ajax response.
1030 # See JavaScriptGenerator for more information.
1031 #
1032 # Example:
1033 #
1034 # update_page do |page|
1035 # page.hide 'spinner'
1036 # end
1037 def update_page(&block)
1038 JavaScriptGenerator.new(@template, &block).to_s
1039 end
1040
1041 # Works like update_page but wraps the generated JavaScript in a <script>
1042 # tag. Use this to include generated JavaScript in an ERb template.
1043 # See JavaScriptGenerator for more information.
1044 #
1045 # +html_options+ may be a hash of <script> attributes to be passed
1046 # to ActionView::Helpers::JavaScriptHelper#javascript_tag.
1047 def update_page_tag(html_options = {}, &block)
1048 javascript_tag update_page(&block), html_options
1049 end
1050
1051 protected
1052 def options_for_ajax(options)
1053 js_options = build_callbacks(options)
1054
1055 js_options['asynchronous'] = options[:type] != :synchronous
1056 js_options['method'] = method_option_to_s(options[:method]) if options[:method]
1057 js_options['insertion'] = "'#{options[:position].to_s.downcase}'" if options[:position]
1058 js_options['evalScripts'] = options[:script].nil? || options[:script]
1059
1060 if options[:form]
1061 js_options['parameters'] = 'Form.serialize(this)'
1062 elsif options[:submit]
1063 js_options['parameters'] = "Form.serialize('#{options[:submit]}')"
1064 elsif options[:with]
1065 js_options['parameters'] = options[:with]
1066 end
1067
1068 if protect_against_forgery? && !options[:form]
1069 if js_options['parameters']
1070 js_options['parameters'] << " + '&"
1071 else
1072 js_options['parameters'] = "'"
1073 end
1074 js_options['parameters'] << "#{request_forgery_protection_token}=' + encodeURIComponent('#{escape_javascript form_authenticity_token}')"
1075 end
1076
1077 options_for_javascript(js_options)
1078 end
1079
1080 def method_option_to_s(method)
1081 (method.is_a?(String) and !method.index("'").nil?) ? method : "'#{method}'"
1082 end
1083
1084 def build_observer(klass, name, options = {})
1085 if options[:with] && (options[:with] !~ /[\{=(.]/)
1086 options[:with] = "'#{options[:with]}=' + encodeURIComponent(value)"
1087 else
1088 options[:with] ||= 'value' unless options[:function]
1089 end
1090
1091 callback = options[:function] || remote_function(options)
1092 javascript = "new #{klass}('#{name}', "
1093 javascript << "#{options[:frequency]}, " if options[:frequency]
1094 javascript << "function(element, value) {"
1095 javascript << "#{callback}}"
1096 javascript << ", '#{options[:on]}'" if options[:on]
1097 javascript << ")"
1098 javascript_tag(javascript)
1099 end
1100
1101 def build_callbacks(options)
1102 callbacks = {}
1103 options.each do |callback, code|
1104 if CALLBACKS.include?(callback)
1105 name = 'on' + callback.to_s.capitalize
1106 callbacks[name] = "function(request){#{code}}"
1107 end
1108 end
1109 callbacks
1110 end
1111 end
1112
1113 # Converts chained method calls on DOM proxy elements into JavaScript chains
1114 class JavaScriptProxy < ActiveSupport::BasicObject #:nodoc:
1115
1116 def initialize(generator, root = nil)
1117 @generator = generator
1118 @generator << root if root
1119 end
1120
1121 private
1122 def method_missing(method, *arguments, &block)
1123 if method.to_s =~ /(.*)=$/
1124 assign($1, arguments.first)
1125 else
1126 call("#{method.to_s.camelize(:lower)}", *arguments, &block)
1127 end
1128 end
1129
1130 def call(function, *arguments, &block)
1131 append_to_function_chain!("#{function}(#{@generator.send(:arguments_for_call, arguments, block)})")
1132 self
1133 end
1134
1135 def assign(variable, value)
1136 append_to_function_chain!("#{variable} = #{@generator.send(:javascript_object_for, value)}")
1137 end
1138
1139 def function_chain
1140 @function_chain ||= @generator.instance_variable_get(:@lines)
1141 end
1142
1143 def append_to_function_chain!(call)
1144 function_chain[-1].chomp!(';')
1145 function_chain[-1] += ".#{call};"
1146 end
1147 end
1148
1149 class JavaScriptElementProxy < JavaScriptProxy #:nodoc:
1150 def initialize(generator, id)
1151 @id = id
1152 super(generator, "$(#{id.to_json})")
1153 end
1154
1155 # Allows access of element attributes through +attribute+. Examples:
1156 #
1157 # page['foo']['style'] # => $('foo').style;
1158 # page['foo']['style']['color'] # => $('blank_slate').style.color;
1159 # page['foo']['style']['color'] = 'red' # => $('blank_slate').style.color = 'red';
1160 # page['foo']['style'].color = 'red' # => $('blank_slate').style.color = 'red';
1161 def [](attribute)
1162 append_to_function_chain!(attribute)
1163 self
1164 end
1165
1166 def []=(variable, value)
1167 assign(variable, value)
1168 end
1169
1170 def replace_html(*options_for_render)
1171 call 'update', @generator.send(:render, *options_for_render)
1172 end
1173
1174 def replace(*options_for_render)
1175 call 'replace', @generator.send(:render, *options_for_render)
1176 end
1177
1178 def reload(options_for_replace = {})
1179 replace(options_for_replace.merge({ :partial => @id.to_s }))
1180 end
1181
1182 end
1183
1184 class JavaScriptVariableProxy < JavaScriptProxy #:nodoc:
1185 def initialize(generator, variable)
1186 @variable = variable
1187 @empty = true # only record lines if we have to. gets rid of unnecessary linebreaks
1188 super(generator)
1189 end
1190
1191 # The JSON Encoder calls this to check for the +to_json+ method
1192 # Since it's a blank slate object, I suppose it responds to anything.
1193 def respond_to?(method)
1194 true
1195 end
1196
1197 def to_json(options = nil)
1198 @variable
1199 end
1200
1201 private
1202 def append_to_function_chain!(call)
1203 @generator << @variable if @empty
1204 @empty = false
1205 super
1206 end
1207 end
1208
1209 class JavaScriptCollectionProxy < JavaScriptProxy #:nodoc:
1210 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
1211 ENUMERABLE_METHODS = ENUMERABLE_METHODS_WITH_RETURN + [:each] unless defined? ENUMERABLE_METHODS
1212 attr_reader :generator
1213 delegate :arguments_for_call, :to => :generator
1214
1215 def initialize(generator, pattern)
1216 super(generator, @pattern = pattern)
1217 end
1218
1219 def each_slice(variable, number, &block)
1220 if block
1221 enumerate :eachSlice, :variable => variable, :method_args => [number], :yield_args => %w(value index), :return => true, &block
1222 else
1223 add_variable_assignment!(variable)
1224 append_enumerable_function!("eachSlice(#{number.to_json});")
1225 end
1226 end
1227
1228 def grep(variable, pattern, &block)
1229 enumerate :grep, :variable => variable, :return => true, :method_args => [pattern], :yield_args => %w(value index), &block
1230 end
1231
1232 def in_groups_of(variable, number, fill_with = nil)
1233 arguments = [number]
1234 arguments << fill_with unless fill_with.nil?
1235 add_variable_assignment!(variable)
1236 append_enumerable_function!("inGroupsOf(#{arguments_for_call arguments});")
1237 end
1238
1239 def inject(variable, memo, &block)
1240 enumerate :inject, :variable => variable, :method_args => [memo], :yield_args => %w(memo value index), :return => true, &block
1241 end
1242
1243 def pluck(variable, property)
1244 add_variable_assignment!(variable)
1245 append_enumerable_function!("pluck(#{property.to_json});")
1246 end
1247
1248 def zip(variable, *arguments, &block)
1249 add_variable_assignment!(variable)
1250 append_enumerable_function!("zip(#{arguments_for_call arguments}")
1251 if block
1252 function_chain[-1] += ", function(array) {"
1253 yield ::ActiveSupport::JSON::Variable.new('array')
1254 add_return_statement!
1255 @generator << '});'
1256 else
1257 function_chain[-1] += ');'
1258 end
1259 end
1260
1261 private
1262 def method_missing(method, *arguments, &block)
1263 if ENUMERABLE_METHODS.include?(method)
1264 returnable = ENUMERABLE_METHODS_WITH_RETURN.include?(method)
1265 variable = arguments.first if returnable
1266 enumerate(method, {:variable => (arguments.first if returnable), :return => returnable, :yield_args => %w(value index)}, &block)
1267 else
1268 super
1269 end
1270 end
1271
1272 # Options
1273 # * variable - name of the variable to set the result of the enumeration to
1274 # * method_args - array of the javascript enumeration method args that occur before the function
1275 # * yield_args - array of the javascript yield args
1276 # * return - true if the enumeration should return the last statement
1277 def enumerate(enumerable, options = {}, &block)
1278 options[:method_args] ||= []
1279 options[:yield_args] ||= []
1280 yield_args = options[:yield_args] * ', '
1281 method_args = arguments_for_call options[:method_args] # foo, bar, function
1282 method_args << ', ' unless method_args.blank?
1283 add_variable_assignment!(options[:variable]) if options[:variable]
1284 append_enumerable_function!("#{enumerable.to_s.camelize(:lower)}(#{method_args}function(#{yield_args}) {")
1285 # only yield as many params as were passed in the block
1286 yield(*options[:yield_args].collect { |p| JavaScriptVariableProxy.new(@generator, p) }[0..block.arity-1])
1287 add_return_statement! if options[:return]
1288 @generator << '});'
1289 end
1290
1291 def add_variable_assignment!(variable)
1292 function_chain.push("var #{variable} = #{function_chain.pop}")
1293 end
1294
1295 def add_return_statement!
1296 unless function_chain.last =~ /return/
1297 function_chain.push("return #{function_chain.pop.chomp(';')};")
1298 end
1299 end
1300
1301 def append_enumerable_function!(call)
1302 function_chain[-1].chomp!(';')
1303 function_chain[-1] += ".#{call}"
1304 end
1305 end
1306
1307 class JavaScriptElementCollectionProxy < JavaScriptCollectionProxy #:nodoc:\
1308 def initialize(generator, pattern)
1309 super(generator, "$$(#{pattern.to_json})")
1310 end
1311 end
1312 end
1313 end
1314
1315 require 'action_view/helpers/javascript_helper'