Skip to content

Instantly share code, notes, and snippets.

@DocX
Created December 14, 2014 16:43
Show Gist options
  • Save DocX/621e43639f6b9f589746 to your computer and use it in GitHub Desktop.
Save DocX/621e43639f6b9f589746 to your computer and use it in GitHub Desktop.
Rails powered API - resource filters by URL params (ie /resources?user_id=12&state=active,finished)
# (c) 2014 Lukas Dolezal ([email protected])
# MIT licence
# include in your base controller (ApplicationController)
# include FilterByParamsHelper
module FilterByParamsHelper
# use in controller:
# @resources = filter_by_params(@resources, params.slice(:user_id, :state))
#
# or
# @resources = filter_by_params(@resources, filterable_params)
# ...
# protected
# def filterable_params
# params.slice(:user_id, :state)
# end
#
# call your URL:
# /resources?user_id=12
# or for select subset by multiple values:
# /resources?user_id=12,34,56&state=valid,finished
#
# notice: values cannot contain commas "," as its used to determine set.
def filter_by_params(resources, filter_params)
filter =
filter_params
.select{|key, val| val.is_a? String}
.map{|key, val|
if val.include?(',')
[key, val.split(',')]
else
[key, val]
end
}
if filter.empty?
resources
else
resources.where(Hash[filter])
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment