Skip to content

Instantly share code, notes, and snippets.

@zerowidth
Created November 8, 2010 18:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zerowidth/668038 to your computer and use it in GitHub Desktop.
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"}} )
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