Skip to content

Instantly share code, notes, and snippets.

@akolosov
Created April 10, 2017 06:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akolosov/7d99b2e04480a4e67885175b8c3b7992 to your computer and use it in GitHub Desktop.
Save akolosov/7d99b2e04480a4e67885175b8c3b7992 to your computer and use it in GitHub Desktop.
module Filterable
extend ActiveSupport::Concern
module ClassMethods
# filter=[created|by_phone=922480|by_id=100..1000]
def filter(filtering_params)
results = self.where(nil)
if filtering_params
filters = filtering_params.gsub(/[\[\]\{\}\'\"\(\)]/, '').split(/[\|]/)
filters.each do |value|
if value.present?
if value.include?('=')
value = value.split(/[\=]/)
if value.respond_to?(:[]) && value.count == 2
if value[1].include?('..')
between = value[1].split(/\.\./)
if between.respond_to?(:[]) && between.count == 2
results = results.public_send(value[0].strip, between[0].strip, between[1].strip)
end
else
results = results.public_send(value[0].strip, value[1].strip)
end
end
else
results = results.public_send(value.strip) if value.present?
end
end
end
end
results.distinct
end
end
end
...
# Возвращает список автомобилей
# @note GET /api/v1/cars
# @example GET /api/v1/cars
def index
@cars = Car.filter(params[:filter])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment