Created
March 11, 2009 14:30
-
-
Save michaelmelanson/77491 to your computer and use it in GitHub Desktop.
See http://www.michaelmelanson.net/post/85530088/in-place-editing-in-rails for an explanation.
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
def editable_content_tag(elemtype, obj, prop, editable=true, options = {}, editOptions = {}, ajaxOptions = {}) | |
objname = obj.class.to_s.downcase | |
options[:url] = url_for(obj) unless options.has_key? :url | |
options[:url] += '.json' | |
options[:id] = dom_id(obj)+"_#{prop}" unless options.has_key? :id | |
ajaxOptions[:method] = 'put' | |
edops = jsonify editOptions | |
ajops = jsonify ajaxOptions | |
contents = obj.send(prop) | |
contents = "(not set)" if contents.blank? | |
tg = content_tag elemtype, | |
contents, | |
options = options | |
if editable then | |
tg += " | |
<script type='text/javascript'>\n | |
new Ajax.InPlaceEditor('#{options[:id]}', '#{options[:url]}', { | |
ajaxOptions: { #{ajops} }, | |
callback: function(form, value) | |
{ return 'authenticity_token=#{form_authenticity_token}&#{objname}[#{prop}]=' + escape(value) }, | |
onComplete: function(transport, element) | |
{ element.innerHTML=transport.responseText.evalJSON().#{objname}.#{prop};}" | |
tg += ",#{edops}" unless edops.empty? | |
tg += "});\n" | |
tg += " </script>\n" | |
end | |
end | |
#stupid helper helper to convert a hash into a JSON options list | |
# (without the encompasing {}'s or any type of recursion | |
#Is there a rails API function that does this? | |
def jsonify hsh | |
str = '' | |
first = true | |
hsh.each do |k,v| | |
str += ', ' unless first | |
str += "#{k}: " | |
str += "'" unless (v.class == Fixnum or v.class == Float) | |
str += v.to_s | |
str += "'" unless (v.class == Fixnum or v.class == Float) | |
first = false | |
end | |
str | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment