Created
April 13, 2011 18:55
-
-
Save codeodor/918140 to your computer and use it in GitHub Desktop.
What's a better name for this function, and how do you better accomplish the same task?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Pass the container name, ID variable name, and options with those names | |
# surrounded by ## on either side, and this function will replace those, | |
# closing the string and referring to a javascript variable in each place | |
# | |
# An example of when it's useful: Suppose you have a set of lists on screen | |
# with some items. You periodically want to refresh the items for one of | |
# the lists, and you don't want to generate the same function for each list | |
# in the page. Instead, you'd rather just have one function and pass the ID | |
# of the list to it, and figure out the DOM ID and route based on the ID | |
# passed to the javascript function. | |
# | |
# function loadModel(id) { | |
# var container = $('list_items_' + id); | |
# <%= remote_function(:update=>'WTF, how do I know? at Ruby run-time?', | |
# :url=>url_for('again, how do I know here?')) %> | |
# } | |
# | |
# With this function, you do this instead: | |
# function loadList(id){ | |
# var container = $('list_items_' + id); | |
# <%= remote_function_with_container_and_id_from_javascript("container", "id", | |
# :update=>'##container##', :url=>list_todos_path('##id##')) %> | |
# } | |
def remote_function_with_container_and_id_from_javascript(container_variable_name, | |
id_variable_name, options) | |
unless options[:update] =~ /###{container_variable_name}##/ | |
raise "Could not find the container variable name in the :update option: #{options[:update].inspect}" | |
end | |
unless options[:url] =~ /%23%23#{id_variable_name}%23%23/ | |
raise "Could not find the ID variable name in the :url option: #{options[:url].inspect}" | |
end | |
updater_string = remote_function(options) | |
updater_string.sub!(/['"]###{container_variable_name}##['"]/, container_variable_name) | |
updater_string.sub!(/(['"])(.+?)%23%23#{id_variable_name}%23%23(.+?)(['"])/){ | |
"#{$1}#{$2}#{$1} + #{id_variable_name} + #{$1}#{$3}#{$1}" | |
} | |
return updater_string | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment