Module: ActionView::Helpers::PrototypeHelper::JavaScriptGenerator::GeneratorMethods
JavaScriptGenerator generates blocks of JavaScript code that allow you to change the content and presentation of multiple DOM elements. Use this in your Ajax response bodies, either in a <script> tag or as plain JavaScript sent with a Content-type of "text/javascript".
Create new instances with PrototypeHelper#update_page or with ActionController::Base#render, then call insert_html, replace_html, remove, show, hide, visual_effect, or any other of the built-in methods on the yielded generator in any order you like to modify the content and appearance of the current page.
Example:
# Generates:
# new Insertion.Bottom("list", "<li>Some item</li>");
# new Effect.Highlight("list");
# ["status-indicator", "cancel-link"].each(Element.hide);
update_page do |page|
page.insert_html :bottom, 'list', "<li>#{@item.name}</li>"
page.visual_effect :highlight, 'list'
page.hide 'status-indicator', 'cancel-link'
end
Helper methods can be used in conjunction with JavaScriptGenerator. When a helper method is called inside an update block on the page object, that method will also have access to a page object.
Example:
module ApplicationHelper
def update_time
page.replace_html 'time', Time.now.to_s(:db)
page.visual_effect :highlight, 'time'
end
end
# Controller action
def poll
render(:update) { |page| page.update_time }
end
You can also use PrototypeHelper#update_page_tag instead of PrototypeHelper#update_page to wrap the generated JavaScript in a <script> tag.
Public Instance Methods
<< (javascript)
Writes raw JavaScript to the page.
Example:
page << "alert('JavaScript with Prototype.');"
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 890 890: def <<(javascript) 891: @lines << javascript 892: end
[] (id)
Returns a element reference by finding it through id in the DOM. This element can then be used for further method calls. Examples:
page['blank_slate'] # => $('blank_slate');
page['blank_slate'].show # => $('blank_slate').show();
page['blank_slate'].show('first').up # => $('blank_slate').show('first').up();
You can also pass in a record, which will use ActionController::RecordIdentifier.dom_id to lookup the correct id:
page[@post] # => $('post_45')
page[Post.new] # => $('new_post')
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 660 660: def [](id) 661: case id 662: when String, Symbol, NilClass 663: JavaScriptElementProxy.new(self, id) 664: else 665: JavaScriptElementProxy.new(self, ActionController::RecordIdentifier.dom_id(id)) 666: end 667: end
alert (message)
Displays an alert dialog with the given message.
Example:
# Generates: alert('This message is from Rails!')
page.alert('This message is from Rails!')
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 832 832: def alert(message) 833: call 'alert', message 834: end
assign (variable, value)
Assigns the JavaScript variable the given value.
Examples:
# Generates: my_string = "This is mine!"; page.assign 'my_string', 'This is mine!' # Generates: record_count = 33; page.assign 'record_count', 33 # Generates: tabulated_total = 47 page.assign 'tabulated_total', @total_from_cart
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 881 881: def assign(variable, value) 882: record "#{variable} = #{javascript_object_for(value)}" 883: end
call (function, *arguments, &block)
Calls the JavaScript function, optionally with the given arguments.
If a block is given, the block will be passed to a new JavaScriptGenerator; the resulting JavaScript code will then be wrapped inside function() { … } and passed as the called function‘s final argument.
Examples:
# Generates: Element.replace(my_element, "My content to replace with.")
page.call 'Element.replace', 'my_element', "My content to replace with."
# Generates: alert('My message!')
page.call 'alert', 'My message!'
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 864 864: def call(function, *arguments, &block) 865: record "#{function}(#{arguments_for_call(arguments, block)})" 866: end
delay (seconds = 1) {|| ...}
Executes the content of the block after a delay of seconds. Example:
# Generates:
# setTimeout(function() {
# ;
# new Effect.Fade("notice",{});
# }, 20000);
page.delay(20) do
page.visual_effect :fade, 'notice'
end
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 904 904: def delay(seconds = 1) 905: record "setTimeout(function() {\n\n" 906: yield 907: record "}, #{(seconds * 1000).to_i})" 908: end
draggable (id, options = {})
Creates a script.aculo.us draggable element. See ActionView::Helpers::ScriptaculousHelper for more information.
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 926 926: def draggable(id, options = {}) 927: record @context.send(:draggable_element_js, id, options) 928: end
drop_receiving (id, options = {})
Creates a script.aculo.us drop receiving element. See ActionView::Helpers::ScriptaculousHelper for more information.
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 932 932: def drop_receiving(id, options = {}) 933: record @context.send(:drop_receiving_element_js, id, options) 934: end
hide (*ids)
Hides the visible DOM elements with the given ids.
Example:
# Hide a few people # Generates: ["person_29", "person_9", "person_0"].each(Element.hide); page.hide 'person_29', 'person_9', 'person_0'
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 810 810: def hide(*ids) 811: loop_on_multiple_args 'Element.hide', ids 812: end
insert_html (position, id, *options_for_render)
Inserts HTML at the specified position relative to the DOM element identified by the given id.
position may be one of:
| :top: | HTML is inserted inside the element, before the element‘s existing content. |
| :bottom: | HTML is inserted inside the element, after the element‘s existing content. |
| :before: | HTML is inserted immediately preceding the element. |
| :after: | HTML is inserted immediately following the element. |
options_for_render may be either a string of HTML to insert, or a hash of options to be passed to ActionView::Base#render. For example:
# Insert the rendered 'navigation' partial just before the DOM
# element with ID 'content'.
# Generates: new Insertion.Before("content", "-- Contents of 'navigation' partial --");
insert_html :before, 'content', :partial => 'navigation'
# Add a list item to the bottom of the <ul> with ID 'list'.
# Generates: new Insertion.Bottom("list", "<li>Last item</li>");
insert_html :bottom, 'list', '<li>Last item</li>'
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 725 725: def insert_html(position, id, *options_for_render) 726: insertion = position.to_s.camelize 727: call "new Insertion.#{insertion}", id, render(*options_for_render) 728: end
literal (code)
Returns an object whose to_json evaluates to code. Use this to pass a literal JavaScript expression as an argument to another JavaScriptGenerator method.
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 671 671: def literal(code) 672: ActiveSupport::JSON::Variable.new(code.to_s) 673: end
redirect_to (location)
Redirects the browser to the given location using JavaScript, in the same form as url_for.
Examples:
# Generates: window.location.href = "/mycontroller"; page.redirect_to(:action => 'index') # Generates: window.location.href = "/account/signup"; page.redirect_to(:controller => 'account', :action => 'signup')
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 845 845: def redirect_to(location) 846: url = location.is_a?(String) ? location : @context.url_for(location) 847: record "window.location.href = #{url.inspect}" 848: end
remove (*ids)
Removes the DOM elements with the given ids from the page.
Example:
# Remove a few people # Generates: ["person_23", "person_9", "person_2"].each(Element.remove); page.remove 'person_23', 'person_9', 'person_2'
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 786 786: def remove(*ids) 787: loop_on_multiple_args 'Element.remove', ids 788: end
replace (id, *options_for_render)
Replaces the "outer HTML" (i.e., the entire element, not just its contents) of the DOM element with the given id.
options_for_render may be either a string of HTML to insert, or a hash of options to be passed to ActionView::Base#render. For example:
# Replace the DOM element having ID 'person-45' with the # 'person' partial for the appropriate object. replace 'person-45', :partial => 'person', :object => @person
This allows the same partial that is used for the insert_html to be also used for the input to replace without resorting to the use of wrapper elements.
Examples:
<div id="people">
<%= render :partial => 'person', :collection => @people %>
</div>
# Insert a new person
#
# Generates: new Insertion.Bottom({object: "Matz", partial: "person"}, "");
page.insert_html :bottom, :partial => 'person', :object => @person
# Replace an existing person
# Generates: Element.replace("person_45", "-- Contents of partial --");
page.replace 'person_45', :partial => 'person', :object => @person
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 774 774: def replace(id, *options_for_render) 775: call 'Element.replace', id, render(*options_for_render) 776: end
replace_html (id, *options_for_render)
Replaces the inner HTML of the DOM element with the given id.
options_for_render may be either a string of HTML to insert, or a hash of options to be passed to ActionView::Base#render. For example:
# Replace the HTML of the DOM element having ID 'person-45' with the
# 'person' partial for the appropriate object.
# Generates: Element.update("person-45", "-- Contents of 'person' partial --");
replace_html 'person-45', :partial => 'person', :object => @person
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 740 740: def replace_html(id, *options_for_render) 741: call 'Element.update', id, render(*options_for_render) 742: end
select (pattern)
Returns a collection reference by finding it through a CSS pattern in the DOM. This collection can then be used for further method calls. Examples:
page.select('p') # => $$('p');
page.select('p.welcome b').first # => $$('p.welcome b').first();
page.select('p.welcome b').first.hide # => $$('p.welcome b').first().hide();
You can also use prototype enumerations with the collection. Observe:
# Generates: $$('#items li').each(function(value) { value.hide(); });
page.select('#items li').each do |value|
value.hide
end
Though you can call the block param anything you want, they are always rendered in the javascript as ‘value, index.’ Other enumerations, like collect() return the last statement:
# Generates: var hidden = $$('#items li').collect(function(value, index) { return value.hide(); });
page.select('#items li').collect('hidden') do |item|
item.hide
end
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 697 697: def select(pattern) 698: JavaScriptElementCollectionProxy.new(self, pattern) 699: end
show (*ids)
Shows hidden DOM elements with the given ids.
Example:
# Show a few people # Generates: ["person_6", "person_13", "person_223"].each(Element.show); page.show 'person_6', 'person_13', 'person_223'
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 798 798: def show(*ids) 799: loop_on_multiple_args 'Element.show', ids 800: end
sortable (id, options = {})
Creates a script.aculo.us sortable element. Useful to recreate sortable elements after items get added or deleted. See ActionView::Helpers::ScriptaculousHelper for more information.
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 920 920: def sortable(id, options = {}) 921: record @context.send(:sortable_element_js, id, options) 922: end
to_s (
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 638 638: def to_s #nodoc 639: returning javascript = @lines * $/ do 640: if ActionView::Base.debug_rjs 641: source = javascript.dup 642: javascript.replace "try {\n#{source}\n} catch (e) " 643: javascript << "{ alert('RJS error:\\n\\n' + e.toString()); alert('#{source.gsub('\\','\0\0').gsub(/\r\n|\n|\r/, "\\n").gsub(/["']/) { |m| "\\#{m}" }}'); throw e }" 644: end 645: end 646: end
toggle (*ids)
Toggles the visibility of the DOM elements with the given ids. Example:
# Show a few people # Generates: ["person_14", "person_12", "person_23"].each(Element.toggle); page.toggle 'person_14', 'person_12', 'person_23' # Hides the elements page.toggle 'person_14', 'person_12', 'person_23' # Shows the previously hidden elements
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 822 822: def toggle(*ids) 823: loop_on_multiple_args 'Element.toggle', ids 824: end
visual_effect (name, id = nil, options = {})
Starts a script.aculo.us visual effect. See ActionView::Helpers::ScriptaculousHelper for more information.
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 912 912: def visual_effect(name, id = nil, options = {}) 913: record @context.send(:visual_effect, name, id, options) 914: end
Private Instance Methods
arguments_for_call (arguments, block = nil)
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 967 967: def arguments_for_call(arguments, block = nil) 968: arguments << block_to_function(block) if block 969: arguments.map { |argument| javascript_object_for(argument) }.join ', ' 970: end
block_to_function (block)
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 972 972: def block_to_function(block) 973: generator = self.class.new(@context, &block) 974: literal("function() { #{generator.to_s} }") 975: end
javascript_object_for (object)
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 963 963: def javascript_object_for(object) 964: object.respond_to?(:to_json) ? object.to_json : object.inspect 965: end
loop_on_multiple_args (method, ids)
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 937 937: def loop_on_multiple_args(method, ids) 938: record(ids.size>1 ? 939: "#{javascript_object_for(ids)}.each(#{method})" : 940: "#{method}(#{ids.first.to_json})") 941: end
method_missing (method, *arguments)
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 977 977: def method_missing(method, *arguments) 978: JavaScriptProxy.new(self, method.to_s.camelize) 979: end
page ()
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 943 943: def page 944: self 945: end
record (line)
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 947 947: def record(line) 948: returning line = "#{line.to_s.chomp.gsub(/\;\z/, '')};" do 949: self << line 950: end 951: end
render (*options_for_render)
# File vendor/rails/actionpack/lib/action_view/helpers/prototype_helper.rb, line 953 953: def render(*options_for_render) 954: old_format = @context && @context.template_format 955: @context.template_format = :html if @context 956: Hash === options_for_render.first ? 957: @context.render(*options_for_render) : 958: options_for_render.first.to_s 959: ensure 960: @context.template_format = old_format if @context 961: end