Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2016
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. def as_json(options={})
  2. # options hash accepts four keys for better customization :only, :methods, :include, :except
  3. # so whenever such keys are found, we call super with those keys to provide response consisting only those keys
  4. if options.key?(:only) or options.key?(:methods) or options.key?(:include) or options.key?(:except)
  5. h = super(options)
  6. else
  7. h = super(only: [:picture, :age],
  8. methods: [:name],
  9. include: {:emails => { :only => [:id, :email] })
  10. end
  11. end
  12. # response when no options passed:
  13. # ex. render json: @user
  14. # user: {
  15. # picture: "url",
  16. # age: "20",
  17. # name: "some name",
  18. # emails: [
  19. # {
  20. # id: 1,
  21. # email: "somename@gmail.com"
  22. # },
  23. # {
  24. # id: 2,
  25. # email: "somename@yahoo.com"
  26. # }
  27. # ]
  28. # }
  29. # response when options passed
  30. # ex: render json: @user.as_json(only: [:picture, :age], methods: [:name])
  31. # user: {
  32. # picture: "url",
  33. # age: "20",
  34. # name: "some name"
  35. # }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement