Created
April 21, 2016 07:40
-
-
Save sevenseacat/89ce49e6002c468d57c33d95b2bb50f6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 ResourceSearchForm | |
include ActiveModel::Model | |
attr_accessor :keywords, :categories, :types, :start_date, :end_date | |
def model_name | |
ActiveModel::Name.new(self, nil, "search") | |
end | |
def initialize(params) | |
self.keywords = params[:keywords] | |
self.categories = Array.wrap(params[:categories]).select(&:present?).map(&:to_i) | |
self.types = Array.wrap(params[:types]).select(&:present?) | |
self.start_date = Date.parse(params[:start_date]) if params[:start_date].present? | |
self.end_date = Date.parse(params[:end_date]) if params[:end_date].present? | |
end | |
end |
This file contains hidden or 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 ResourceSearcher | |
attr_accessor :form, :scope | |
def initialize(form, scope) | |
self.form = form | |
self.scope = scope | |
end | |
def results | |
results = scope | |
results = results.search(form.keywords) if form.keywords.present? | |
results = with_date_range(results, form.start_date, form.end_date) | |
results = with_type_filter(results, form.types) | |
results = with_category_filter(results, form.categories) | |
results | |
end | |
private | |
def with_date_range(results, start_date, end_date) | |
results = results.where("published_at >= ? OR published_at IS NULL", start_date) if start_date.present? | |
results = results.where("published_at <= ? OR published_at IS NULL", end_date) if end_date.present? | |
results | |
end | |
def with_type_filter(results, types) | |
results = results.where(type: types) if types.any? | |
results | |
end | |
def with_category_filter(results, categories) | |
if categories.any? | |
results.where(id: results.joins(:categories).where(resource_categories: {id: categories})) | |
else | |
results | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment