Created
September 24, 2009 13:24
-
-
Save kplawver/192732 to your computer and use it in GitHub Desktop.
Adds :callback option to to_json for Array, Hash and ActiveRecord::Base.
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
# 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