Guest User

Untitled

a guest
Jul 17th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. require 'set'
  2. require 'active_model'
  3. require 'active_support/core_ext/class'
  4. require 'json'
  5. require 'acts_as_api'
  6.  
  7. class Customer
  8. attr_accessor :firstname, :lastname, :age, :sex, :phone, :orders
  9.  
  10. include ActiveModel::Serializers::Xml
  11.  
  12. extend ActsAsApi::Base
  13. acts_as_api
  14. api_accessible :default => [ :firstname, :lastname ],
  15. :v1_public => [ :firstname, :age ],
  16. :v2_public => [ :firstname, :age, :sex ],
  17.  
  18. :v1_private => [ :firstname, :lastname, :age, :sex ],
  19. :v2_private => [ :firstname, :lastname, :age, :sex, :phone, :orders ]
  20.  
  21. def initialize(opts)
  22. opts.each do |k,v|
  23. self.send :"#{k}=", v
  24. end
  25. end
  26.  
  27. def model_name
  28. 'customer'
  29. end
  30.  
  31. end
  32.  
  33. class Order
  34. attr_accessor :items, :total
  35.  
  36. extend ActsAsApi::Base
  37. acts_as_api
  38. api_accessible :v2_public => [ :items ],
  39. :v2_private => [ :items, :total ]
  40.  
  41. def initialize(opts)
  42. opts.each do |k,v|
  43. self.send :"#{k}=", v
  44. end
  45. end
  46.  
  47. end
  48.  
  49. # jsut a render stub
  50. def render(text)
  51. case
  52. when text[:json] && text[:xml]
  53. raise "XML or JSON?"
  54. when text[:json]
  55. puts text[:json].to_json
  56. when text[:xml]
  57. puts text[:xml].to_xml
  58. end
  59. end
  60.  
  61. def api_template(version = :v2, template = :public)
  62. "#{version.to_s}_#{template.to_s}".to_sym
  63. end
  64.  
  65. include ActsAsApi::Rendering
  66.  
  67. orders = []
  68. 10.times do
  69. orders << Order.new(:total => rand(100), :items => %w{a b c d e f g h i j}.select{rand > 0.6})
  70. end
  71.  
  72. @customer = Customer.new :firstname => 'niko', :lastname => 'dittmann', :age => 35, :sex => :male, :phone => '959532', :orders => orders
  73.  
  74. render_for_api :default, :xml => @customer
  75. render_for_api :default, :json => @customer
  76. render_for_api api_template, :xml => @customer
  77. render_for_api api_template(:v2, :private), :json => @customer, :root => 'foo'
Add Comment
Please, Sign In to add comment