Guest User

Untitled

a guest
Dec 9th, 2013
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.45 KB | None | 0 0
  1. class Friendship
  2.   include DataMapper::Resource
  3.  
  4.   property :id, Serial
  5.   property :created_at, DateTime
  6.  
  7.   belongs_to :source, 'User', :key => true
  8.   belongs_to :target, 'User', :key => true
  9.  
  10.   validates_presence_of :source
  11.   validates_presence_of :target
  12. end
  13.  
  14.  
  15. class User
  16.   include DataMapper::Resource
  17.  
  18.   property :id, Serial
  19.   property :email, String, :required => true, :format => :email_address, :unique => true
  20.   property :password, BCryptHash, :required => true
  21.   property :avatar_url, String
  22.   property :phone_number, BCryptHash, :unique => true
  23.   property :created_at, DateTime
  24.  
  25.   has n, :friendships, :child_key => [ :source_id ]
  26.   has n, :friends, self, :through => :friendships, :via => :target
  27.   has n, :votes
  28.   has n, :favorites
  29.   has n, :memberships
  30.  
  31.   def polls_voted_on
  32.     self.votes.map { |v| v.option.poll }
  33.   end
  34.  
  35.   def polls_favorited
  36.     self.favorites.map(&:poll)
  37.   end
  38. end
  39.  
  40. class Qurb < Sinatra::Application
  41.   post '/users/:user_id/friendships' do
  42.     friendship = Friendship.new(:source_id => params[:user_id], :target_id => params[:friend_id])
  43.     if friendship.save
  44.       {friendship: friendship}.to_json
  45.     else
  46.       {errors: friendship.errors.to_h}.to_json
  47.     end
  48.   end
  49.  
  50.   get '/user/:user_id/friendships' do
  51.     user = User.first(:id => params[:user_id])
  52.     if user
  53.       {friends: user.friendships.to_h}.to_json
  54.     else
  55.       {errors: friendships.errors.to_h}.to_json
  56.     end
  57.   end
  58. end
Advertisement
Add Comment
Please, Sign In to add comment