Skip to content

Commit

Permalink
refactor model user
Browse files Browse the repository at this point in the history
  • Loading branch information
citin committed Jul 13, 2019
1 parent c4eb064 commit 5a6f98f
Show file tree
Hide file tree
Showing 4 changed files with 10 additions and 22 deletions.
5 changes: 4 additions & 1 deletion app/controllers/api/v1/users_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@ class Api::V1::UsersController < ApplicationController
before_action :set_user
before_action :set_purchase_option, only: [:purchase]

class AlreadyPurchasedError < StandardError; end

# POST /api/v1/users/:id/purchase
# Params: { "purchase_option_id": 1 }
def purchase
@user.purchase(@purchase_option)
raise AlreadyPurchasedError if @user.is_in_library?(@purchase_option.content)
Purchase.create(user: @user, purchase_option: @purchase_option)
render json: @user.library
end

Expand Down
10 changes: 5 additions & 5 deletions app/controllers/application_controller.rb
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
class ApplicationController < ActionController::API
rescue_from User::AlreadyPurchasedError, with: :render_method_not_allowed
rescue_from Api::V1::UsersController::AlreadyPurchasedError, with: :render_method_not_allowed
rescue_from ActiveRecord::RecordNotFound, with: :render_not_found_response

def render_not_found_response(exception)
render json: { error: exception.message }, status: :not_found
end

def render_method_not_allowed(exception)
render json: { error: exception.message }, status: 405
end

def render_not_found_response(exception)
render json: { error: exception.message }, status: :not_found
end
end
13 changes: 1 addition & 12 deletions app/models/user.rb
Original file line number Diff line number Diff line change
@@ -1,23 +1,12 @@
class User < ApplicationRecord

class AlreadyPurchasedError < StandardError; end

has_many :purchases

def library
self.purchases.select {|p| p.alive? }.sort_by(&:remaining_time)
end

def purchase(purchase_option)
if is_in_library?(purchase_option.content)
raise AlreadyPurchasedError
else
self.purchases << Purchase.create(purchase_option: purchase_option)
end
end

private

# check by title
def is_in_library?(content)
library.any? {|purchase| purchase.content.title == content.title }
end
Expand Down
4 changes: 0 additions & 4 deletions spec/models/user_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,6 @@
expect(user.library.size).to eql(3)
end

it "can't purchase a content that is in the library" do
expect{ user.purchase(user.library.first.purchase_option) }.to raise_error(User::AlreadyPurchasedError)
end

it "library is ordered by purchase's remaining time" do
user.purchases.last.update(created_at: 1.day.ago)

Expand Down

0 comments on commit 5a6f98f

Please sign in to comment.