Last active
March 10, 2017 02:24
-
-
Save nicooga/bce85207baedbebc9d9586a588f9a2ce 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
module Search | |
def run(query, params) | |
filters.inject(query) do |memo, filter| | |
filter.call(memo, params) | |
end | |
end | |
def filter(arg, options = {}) | |
case arg | |
when Symbol | |
def_simple_filter(arg, options) | |
when Hash | |
def_complex_filter(arg, options) | |
end | |
end | |
private | |
def filters | |
@filters ||= [] | |
end | |
def def_simple_filter(attr, options = {}) | |
filters.push(-> (query, params) do | |
params.key?(attr) ? | |
query.where(attr => params[attr]) : | |
query | |
end) | |
end | |
def def_complex_filter(hash, options = {}) | |
raise NotImplementedError | |
end | |
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
UserSearch.run(User.all, name: 'Pepe', email: 'Lapone@gmail.com') |
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
module User::Search | |
extend ::Search | |
filter :name | |
filter :email, operation: :matches | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment