Last active
January 3, 2016 03:09
-
-
Save yvasilkov/8400444 to your computer and use it in GitHub Desktop.
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
class LeadsController < ApplicationController | |
def index | |
collection = Collections::LeadsCollection.new(current_ability, current_user, params) | |
@leads = collection.eager_loaded.paginated.items | |
end | |
end | |
module Collections | |
class Collection | |
module Authorization | |
def items | |
super.accessible_by(ability) | |
end | |
end | |
module Ordering | |
def items | |
if has_custom_ordering? | |
super.reorder(ordering_sql) | |
else | |
super.sorted_by_date | |
end | |
end | |
private | |
def has_custom_ordering? | |
order_key.present? | |
end | |
def ordering_sql | |
keys = order_key.split(',') | |
keys.map { |k| "#{k} #{order_dir}" }.join(',') | |
end | |
def order_key | |
params[:order_key] | |
end | |
def order_dir | |
params[:order_dir] =~ /^desc$/i ? 'desc' : 'asc' | |
end | |
end | |
module Pagination | |
def items | |
super.page(params[:page]).per(params[:per]) | |
end | |
end | |
module Search | |
def items | |
super.search_for(params[:search]) | |
end | |
end | |
end | |
end | |
module Collections | |
class LeadsCollection < Collection | |
module Scope | |
def items | |
super | |
end | |
end | |
module LeadsStatusScope | |
def items | |
super.in_status(params[:lead_status]) | |
end | |
end | |
module DepartmentScope | |
def items | |
department_ids.include?(params[:department]) ? super.with_department(params[:department]) : super | |
end | |
private | |
def department_ids | |
Deprtment.all.select(:id).map(&:id).map(&:to_s) | |
end | |
end | |
module RoleScope | |
def items | |
params[:role].present? ? super.with_role(params[:role]) : super | |
end | |
end | |
module HasQualificationScope | |
def items | |
params[:has_qualification].present? ? super.with_qualification(params[:has_qualification]) : super | |
end | |
end | |
def EagerLoaded | |
def items | |
super.includes(:details, :matches, :comments) | |
end | |
end | |
attr_reader :ability, :user, :params | |
def initialize(ability, user, params) | |
@ability = ability | |
@user = user | |
@params = params | |
extend Scope, LeadStatusScope, DepartmentScope, RoleScope, HasQualificationScope, Search | |
end | |
def items | |
# default scope for collection can be applied here | |
Prospect.scoped_for_user(user, params[:scope]) | |
end | |
def eager_loaded | |
extend EagerLoaded | |
self | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment