Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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"
- # }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement