Created
January 15, 2016 06:57
-
-
Save the-undefined/6d55a55fec699b7b4e04 to your computer and use it in GitHub Desktop.
command pattern to build queries based on conditions
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
module Index | |
module_function | |
def call(parent:, search_term:, sort:, direction:) | |
queries = [ | |
parent_query(parent), | |
search_query(search_term), | |
sort_query(sort, direction) | |
] | |
queries.inject(Owner.includes(:user)) do |query,collection| | |
collection.call(query) | |
end | |
end | |
private | |
module_function | |
def noop_call | |
->(collection) { collection } | |
end | |
def sort_query(sort_column, direction) | |
return noop_call unless sort_column | |
sort_direction = direction == 'DESC' ? :desc : :asc | |
->(collection) { collection.order(sort_column => sort_direction) } | |
end | |
def search_query(search_term) | |
return noop_call unless search_term.present? | |
->(collection) { collection.search(search_term) } | |
end | |
def parent_query(parent) | |
return noop_call unless parent? | |
->(collection) { | |
collection | |
.joins(:parent) | |
.where(parents: { id: parent }) | |
} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment