Skip to content

Instantly share code, notes, and snippets.

@xdougx
Last active July 20, 2016 14:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save xdougx/39a87a7f50b7d1f59f70 to your computer and use it in GitHub Desktop.
Save xdougx/39a87a7f50b7d1f59f70 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
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