Created
November 8, 2010 18:28
-
-
Save zerowidth/668038 to your computer and use it in GitHub Desktop.
fix mongo mapper's as_json so it handles :include with sub-options (e.g. :include => {:foos => {:only => "name"}} )
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
module App | |
class Model | |
def as_json(opts={}) | |
hash = super | |
if opts && inclusions = opts[:include] | |
case inclusions | |
when Array | |
inclusions.each do |key| | |
hash[key.to_s] = send(key.to_sym).as_json | |
end | |
when Hash | |
inclusions.each do |key, sub_opts| | |
hash[key.to_s] = send(key.to_sym).as_json.map {|r| r.as_json(sub_opts) } | |
end | |
when String, Symbol | |
hash[inclusions.to_s] = send(inclusions.to_sym).as_json.map(&:as_json) | |
end | |
end | |
hash | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment