Skip to content

Instantly share code, notes, and snippets.

@8parth
Last active October 22, 2016 12:06
Show Gist options
  • Save 8parth/56d33716b55535012e34428f8b924b23 to your computer and use it in GitHub Desktop.
Save 8parth/56d33716b55535012e34428f8b924b23 to your computer and use it in GitHub Desktop.
to show how as_json can be used with super
def as_json(options={})
# options hash accepts four keys for better customization :only, :methods, :include, :except
# so whenever such keys are found, we call super with those keys to provide response consisting only those keys
if options.key?(:only) or options.key?(:methods) or options.key?(:include) or options.key?(:except)
h = super(options)
else
h = super(only: [:picture, :age],
methods: [:name],
include: {:emails => { :only => [:id, :email] })
end
end
# response when no options passed:
# ex. render json: @user
# user: {
# picture: "url",
# age: "20",
# name: "some name",
# emails: [
# {
# id: 1,
# email: "somename@gmail.com"
# },
# {
# id: 2,
# email: "somename@yahoo.com"
# }
# ]
# }
# response when options passed
# ex: render json: @user.as_json(only: [:picture, :age], methods: [:name])
# user: {
# picture: "url",
# age: "20",
# name: "some name"
# }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment