Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #933: upload_progress_send_ajax.rb

File upload_progress_send_ajax.rb, 2.2 kB (added by madrobby, 4 years ago)

Slightly expanded version to use it in helpers, adds an optional "text" parameter

Line 
1 # helper function to send a javascript command to the client.
2  # options hash should have:
3  # :action => (:insert, :replace, :delete, :empty, :formfill)
4  # :target => DOM element. (string name)
5  # :position => (:before, :top, :bottom, :after)
6  #   postion is only used in the insert routines
7  # :formobject => ActiveRecord Object - values to fill into form
8  #   :formobject is used only by :formfill action
9  # pass in a block of captured erb html for functions that make sense to do so.
10  def send_ajax(options, text = "", &block)
11    
12    if block then
13      # execute the block= 
14      # this code stolen from the capture helper
15      buffer = eval("_erbout", block.binding)
16      pos = buffer.length
17      block.call
18      
19      # extract the block
20      data = buffer[pos..-1]
21      
22      # replace it in the original with empty string
23      buffer[pos..-1] = ''
24      text = data
25    end
26    
27    text = escape_javascript(text)
28      
29    case options[:action]
30      when :insert
31        case options[:position]
32          when :before
33            "new Insertion.Before('#{options[:target]}', '#{text}')"
34          when :top
35            "new Insertion.Top('#{options[:target]}', '#{text}')"
36          when :bottom
37            "new Insertion.Bottom('#{options[:target]}', '#{text}')"
38          when :after
39            "new Insertion.After('#{options[:target]}', '#{text}')"
40          else
41            raise ArgumentError, "Invalid position, choose one of :before, :top, :bottom, :after"
42        end
43      when :replace
44        "$('#{options[:target]}').innerHTML = '#{text}'"         
45      when :empty
46        "$('#{options[:target]}').innerHTML = ''"
47      when :delete
48        "$('#{options[:target]}').parentNode.removeChild($('#{options[:target]}'))"
49      when :formfill
50        raise ArgumentError, ":formfill requires :formobject" unless options[:formobject]
51        ret = ''
52        objectname = options[:formobject].class.to_s.underscore
53        for key,value in options[:formobject].attributes
54          ret << "$('#{objectname}_#{key}').value = '#{escape_javascript(value.to_s)}'\n"
55        end
56        return ret
57      else
58        raise ArgumentError, "Invalid action, choose one of :insert, :replace, :delete, :empty, :formfill"
59    end
60  
61  end