-
Notifications
You must be signed in to change notification settings - Fork 312
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add basic limiting & ordering to payments API
- Loading branch information
Dan Hansen
committed
Jan 30, 2014
1 parent
9c3bfac
commit 7e86e3a
Showing
2 changed files
with
121 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,42 @@ | ||
class Api::V0::PaymentsController < Api::V0::BaseController | ||
ALLOWED_ORDER_BY_ATTRIBUTES = ['created_at', 'updated_at', 'ct_payment_id', 'status'] | ||
|
||
def index | ||
campaign = Campaign.find_by_id!(params[:campaign_id]) | ||
render json: campaign.payments | ||
resource = ApiResource.new(campaign.payments, params) | ||
resource.apply_filters! | ||
|
||
render json: resource.relation | ||
end | ||
end | ||
|
||
private | ||
|
||
class ApiResource < Struct.new(:relation, :params) | ||
def apply_filters! | ||
self.relation = apply_limit!(relation) if apply_limit? | ||
self.relation = apply_order!(relation) if apply_order? | ||
end | ||
|
||
def apply_limit!(relation) | ||
relation.limit(params[:limit]) | ||
end | ||
|
||
def apply_order!(relation) | ||
relation.order("#{params[:order_by]} #{order_direction}") | ||
end | ||
|
||
def apply_order? | ||
String(params[:order_by]).in?(ALLOWED_ORDER_BY_ATTRIBUTES) | ||
end | ||
|
||
def apply_limit? | ||
params[:limit].present? | ||
end | ||
|
||
private | ||
|
||
def order_direction | ||
params[:order_direction] == 'asc' ? 'asc' : 'desc' | ||
end | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters