New AJAX function: remote_replace_with_partial() <-- write l


#1

I hate writing controller actions that support simple lightweight
ajax calls like this:

def show_buttons
render :partial => “home_buttons”
end

So the birth of remote_replace_with_partial
Now you can replace a div elements with any controllers partials and
pass those partials any number of params without having to write
supportive actions in your controllers. This is a great tool for UI
changes on the fly and cancel buttons

Heres the code:
application_helper file:
def remote_replace_with_partial(link, options = {}, params = {})
## For passing params ##
param_string = String.new
params.each {|key,value| param_string << “&#{key}=#{value}” }

 string = link_to_function(link, "update_page_element('#{options

[:update]}’, ‘#{options[:controller]}’, ‘#{options[:partial]}’, ‘#
{param_string}’);")
string
end

application.rb file:
def partial_handler
string = render_to_string :partial => params[:partial]
render :inline => string
end

javascript code: (this can be placed in a JS file or in your template)
<%= javascript_tag "function update_page_element(element_id,
controller ,partial_file, params)
{
new Ajax.Updater(element_id, ‘/’ + controller + ‘/partial_handler?
partial=’ + partial_file + params, {asynchronous:true,
evalScripts:true}); return false;
} " %>

View code:
<%= remote_replace_with_partial(‘change me ajax’, {:update =>
‘tag1’, :controller => ‘forms’, :partial => ‘test’}, { :name => ‘joe
black’, :id => 2}) %>

Please provide as much feedback as possible – I’m a noobe rails hacker

Enjoy,
Chris Larson


#2

Looks good - a high-level comment is that it might be a deviation from
MVC tho?