Module: ActionView::Helpers::PrototypeHelper::JavaScriptGenerator::GeneratorMethods

Defined in:
lib/action_view/helpers/prototype_helper.rb

Overview

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:

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

generates the following JavaScript:

new Insertion.Bottom("list", "<li>Some item</li>");
new Effect.Highlight("list");
["status-indicator", "cancel-link"].each(Element.hide);

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.

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *arguments) ⇒ Object (private)


659
660
661
# File 'lib/action_view/helpers/prototype_helper.rb', line 659

def method_missing(method, *arguments)
  JavaScriptProxy.new(self, method.to_s.camelize)
end

Instance Method Details

#<<(javascript) ⇒ Object

Writes raw JavaScript to the page.


593
594
595
# File 'lib/action_view/helpers/prototype_helper.rb', line 593

def <<(javascript)
  @lines << javascript
end

#[](id) ⇒ Object

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();

451
452
453
# File 'lib/action_view/helpers/prototype_helper.rb', line 451

def [](id)
  JavaScriptElementProxy.new(self, id)
end

#alert(message) ⇒ Object

Displays an alert dialog with the given message.


571
572
573
# File 'lib/action_view/helpers/prototype_helper.rb', line 571

def alert(message)
  call 'alert', message
end

#assign(variable, value) ⇒ Object

Assigns the JavaScript variable the given value.


588
589
590
# File 'lib/action_view/helpers/prototype_helper.rb', line 588

def assign(variable, value)
  record "#{variable} = #{javascript_object_for(value)}"
end

#call(function, *arguments) ⇒ Object

Calls the JavaScript function, optionally with the given arguments.


583
584
585
# File 'lib/action_view/helpers/prototype_helper.rb', line 583

def call(function, *arguments)
  record "#{function}(#{arguments_for_call(arguments)})"
end

#delay(seconds = 1) ⇒ Object

Executes the content of the block after a delay of seconds. Example:

page.delay(20) do
  page.visual_effect :fade, 'notice'
end

602
603
604
605
606
# File 'lib/action_view/helpers/prototype_helper.rb', line 602

def delay(seconds = 1)
  record "setTimeout(function() {\n\n"
  yield
  record "}, #{(seconds * 1000).to_i})"
end

#draggable(id, options = {}) ⇒ Object

Creates a script.aculo.us draggable element. See ActionView::Helpers::ScriptaculousHelper for more information.


624
625
626
# File 'lib/action_view/helpers/prototype_helper.rb', line 624

def draggable(id, options = {})
  record @context.send(:draggable_element_js, id, options)
end

#drop_receiving(id, options = {}) ⇒ Object

Creates a script.aculo.us drop receiving element. See ActionView::Helpers::ScriptaculousHelper for more information.


630
631
632
# File 'lib/action_view/helpers/prototype_helper.rb', line 630

def drop_receiving(id, options = {})
  record @context.send(:drop_receiving_element_js, id, options)
end

#hide(*ids) ⇒ Object

Hides the visible DOM elements with the given ids.


561
562
563
# File 'lib/action_view/helpers/prototype_helper.rb', line 561

def hide(*ids)
  call 'Element.hide', *ids
end

#insert_html(position, id, *options_for_render) ⇒ Object

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 preceeding 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'.
insert_html :before, 'content', :partial => 'navigation'

# Add a list item to the bottom of the <ul> with ID 'list'.
insert_html :bottom, 'list', '<li>Last item</li>'

502
503
504
505
# File 'lib/action_view/helpers/prototype_helper.rb', line 502

def insert_html(position, id, *options_for_render)
  insertion = position.to_s.camelize
  call "new Insertion.#{insertion}", id, render(*options_for_render)
end

#redirect_to(location) ⇒ Object

Redirects the browser to the given location, in the same form as url_for.


577
578
579
# File 'lib/action_view/helpers/prototype_helper.rb', line 577

def redirect_to(location)
  assign 'window.location.href', @context.url_for(location)
end

#remove(*ids) ⇒ Object

Removes the DOM elements with the given ids from the page.


551
552
553
# File 'lib/action_view/helpers/prototype_helper.rb', line 551

def remove(*ids)
  record "#{javascript_object_for(ids)}.each(Element.remove)"
end

#replace(id, *options_for_render) ⇒ Object

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_html '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
page.insert_html :bottom, :partial => 'person', :object => @person

# Replace an existing person
page.replace 'person_45', :partial => 'person', :object => @person

546
547
548
# File 'lib/action_view/helpers/prototype_helper.rb', line 546

def replace(id, *options_for_render)
  call 'Element.replace', id, render(*options_for_render)
end

#replace_html(id, *options_for_render) ⇒ Object

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.
replace_html 'person-45', :partial => 'person', :object => @person

516
517
518
# File 'lib/action_view/helpers/prototype_helper.rb', line 516

def replace_html(id, *options_for_render)
  call 'Element.update', id, render(*options_for_render)
end

#select(pattern) ⇒ Object

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:

page.select('#items li').each do |value|
  value.hide
end 
# => $$('#items li').each(function(value) { value.hide(); });

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:

page.select('#items li').collect('hidden') do |item|
  item.hide
end
# => var hidden = $$('#items li').collect(function(value, index) { return value.hide(); });

476
477
478
# File 'lib/action_view/helpers/prototype_helper.rb', line 476

def select(pattern)
  JavaScriptElementCollectionProxy.new(self, pattern)
end

#show(*ids) ⇒ Object

Shows hidden DOM elements with the given ids.


556
557
558
# File 'lib/action_view/helpers/prototype_helper.rb', line 556

def show(*ids)
  call 'Element.show', *ids
end

#sortable(id, options = {}) ⇒ Object

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.


618
619
620
# File 'lib/action_view/helpers/prototype_helper.rb', line 618

def sortable(id, options = {})
  record @context.send(:sortable_element_js, id, options)
end

#to_sObject

:nodoc:


435
436
437
438
439
440
441
442
443
# File 'lib/action_view/helpers/prototype_helper.rb', line 435

def to_s #:nodoc:
  returning javascript = @lines * $/ do
    if ActionView::Base.debug_rjs
      source = javascript.dup
      javascript.replace "try {\n#{source}\n} catch (e) "
      javascript << "{ alert('RJS error:\\n\\n' + e.toString()); alert('#{source.gsub(/\r\n|\n|\r/, "\\n").gsub(/["']/) { |m| "\\#{m}" }}'); throw e }"
    end
  end
end

#toggle(*ids) ⇒ Object

Toggles the visibility of the DOM elements with the given ids.


566
567
568
# File 'lib/action_view/helpers/prototype_helper.rb', line 566

def toggle(*ids)
  call 'Element.toggle', *ids
end

#visual_effect(name, id = nil, options = {}) ⇒ Object

Starts a script.aculo.us visual effect. See ActionView::Helpers::ScriptaculousHelper for more information.


610
611
612
# File 'lib/action_view/helpers/prototype_helper.rb', line 610

def visual_effect(name, id = nil, options = {})
  record @context.send(:visual_effect, name, id, options)
end