Last active
December 12, 2015 12:38
-
-
Save snikch/4772999 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
def index | |
filters = {} | |
filters[:categories_filter] = params[:categories].split(',') unless params[:categories].blank? | |
filters[:questions_filter] = params[:questions].split(',') unless params[:questions].blank? | |
@questions = QuestionFilter.new(filters).questions | |
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
class QuestionFilter | |
attr_accessible :options | |
def initialize opts = {} | |
@options = default_options.merge opts | |
end | |
def default_options | |
{ | |
questions_filter: [], | |
categories_filter: [], | |
random: false, | |
string_filter: nil | |
} | |
end | |
def questions | |
return @_questions unless @_questions.nil? | |
@_questions = Question.scoped | |
apply_categories_filter if options.categories_filter.size > 0 | |
apply_questions_filter if options.questions_filter.size > 0 | |
apply_random_filter if options.random | |
apply_string_filter if options.string_filter | |
@_questions | |
end | |
private | |
def apply_categories_filter | |
condition_params = options. | |
categories_filter. | |
inject({ id:[], name:[]}){ |hash,value| | |
value.to_i > 0 ? hash[:id].push(value.to_i) : hash[:name].push(value) | |
hash | |
} | |
condition_string = condition_params.inject([]){|array, (key,values)| | |
array << "categories.#{key} IN (:#{key})" if values.size > 0 | |
array | |
} | |
@_questions = @_questions.where(condition_string.join('OR'), condition_params) | |
end | |
def apply_questions_filter | |
@_questions = @_questions. | |
where("questions.id IN (?)", options.questions_filter) | |
end | |
def apply_random_filter | |
@_questions = @_questions.order('random()') | |
end | |
def apply_string_filter | |
@_questions = @_questions.search_for(options.string_filter) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment