Skip to content

Instantly share code, notes, and snippets.

@the-undefined
Last active January 15, 2016 07:01
Show Gist options
  • Save the-undefined/c33e04aa226a2370b120 to your computer and use it in GitHub Desktop.
Save the-undefined/c33e04aa226a2370b120 to your computer and use it in GitHub Desktop.
Sorting, filtering, and searching using the command pattern to apply a list queries to the collection when they meet criteria for usage.
module Index
module_function
def call(parent_filter:, search_term:, sort:, direction:)
queries = [
filter_query(parent_filter),
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 filter_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