Skip to content

Instantly share code, notes, and snippets.

@kplawver
Created September 24, 2009 13:24
Show Gist options
  • Save kplawver/192732 to your computer and use it in GitHub Desktop.
Save kplawver/192732 to your computer and use it in GitHub Desktop.
Adds :callback option to to_json for Array, Hash and ActiveRecord::Base.
# Adds :callback option to to_json for Array, Hash and ActiveRecord::Base. Usage:
# user = User.find(:first)
# user.to_json(:callback => "foo")
# => foo({"user":{"name":"The Dude"}})
# There's probably a much better way to do this - would love ideas / improvements!
class Array
alias orig_to_json to_json
def to_json(*a)
callback = nil
if a[0] && !a[0][:callback].blank?
callback = a[0][:callback]
a[0].delete(:callback)
end
r = self.orig_to_json(a[0])
if callback
r = "#{callback}(#{r})"
end
r
end
end
class Hash
alias orig_to_json to_json
def to_json(*a)
callback = nil
if a[0] && !a[0][:callback].blank?
callback = a[0][:callback]
a[0].delete(:callback)
end
r = self.orig_to_json(a[0])
if callback
r = "#{callback}(#{r})"
end
r
end
end
class ActiveRecord::Base
alias orig_to_json to_json
def to_json(*a)
callback = nil
if a[0] && !a[0][:callback].blank?
callback = a[0][:callback]
a[0].delete(:callback)
end
r = self.orig_to_json(a[0])
if callback
r = "#{callback}(#{r})"
end
r
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment