-
-
Save joseh-henrique/5053e33a1fb059ad2fa5 to your computer and use it in GitHub Desktop.
A intenção era só simplificar e ganhar todos os métodos sem precisar fazer muito, é muito simples fazer em uma classe desprendida do ActiveRecord
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 Searchable | |
included do | |
scope :gender, ->(gender) { where(:gender => gender) } | |
scope :birth_on, ->(date) { where(:birthdate =>date) } | |
scope :birth_before_than, ->(date) { where("#{quoted_table_name}.birthdate < ?", date) } | |
scope :birth_after_than, ->(date) { where("#{quoted_table_name}.birthdate > ?", date) } | |
scope :profile, ->(profile){ where(:profile => profile) } | |
end | |
module ClassMethods | |
def fiter_with(options = {}) | |
relation = all | |
options.each do |key, value| | |
relation = relation.send(key, value) if available_scope?(key) | |
end | |
relation | |
end | |
def available_scope?(scope) | |
%w(gender birth_on birth_before_than birth_after_than profile).include?(scope) | |
end | |
end | |
end | |
# Exemplo: | |
# search = MySearch.new(User) | |
# search.filter_with(options) | |
class MySearch | |
attr_accessor :klass | |
def initialize klass | |
@klass = klass | |
add_scopes(@klass) | |
end | |
def add_scopes(klass) | |
@klass.class_eval do | |
scope :gender, ->(gender) { where(:gender => gender) } | |
scope :birth_on, ->(date) { where(:birthdate =>date) } | |
scope :birth_before_than, ->(date) { where("#{quoted_table_name}.birthdate < ?", date) } | |
scope :birth_after_than, ->(date) { where("#{quoted_table_name}.birthdate > ?", date) } | |
scope :profile, ->(profile){ where(:profile => profile) } | |
end | |
end | |
def fiter_with(options = {}) | |
relation = @klass.all | |
options.each do |key, value| | |
relation = relation.send(key, value) if available_scope?(key) | |
end | |
relation | |
end | |
private | |
def available_scope?(scope) | |
%w(gender birth_on birth_before_than birth_after_than profile).include?(scope) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment