Skip to content

Instantly share code, notes, and snippets.

@lucasmazza
Created July 13, 2023 23:02
Show Gist options
  • Save lucasmazza/77f86d00b2f7417a92921b873cbfedf5 to your computer and use it in GitHub Desktop.
Save lucasmazza/77f86d00b2f7417a92921b873cbfedf5 to your computer and use it in GitHub Desktop.
class ProductSearch < ScopeBuilder::Scope
param :name, :string
param :category, :integer
param :status, :string
order_by :name, :created_at
private
def apply_name_param(scope, value)
scope.search_by_name(value)
end
def apply_category_param(scope, value)
scope.where(category_id: value)
end
def apply_status_param(scope, value, context)
scope.where(status: value) if context[:user].admin?
end
def prepare(scope, params, context)
scope.where('deleted_at IS NULL')
end
end
scope = ProductSearch.new(Product, user: user)
result = scope.build(name: "iPhone", status: "available", order: ["name", "created_at"], dir: "desc")
# result.valid? # => true | false
# result.errors # => ActiveModel::Errors
# result.params # => ProductSearch::Params
render json: { data: result.scope }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment