Skip to content

Instantly share code, notes, and snippets.

@asux
Created July 27, 2018 11:50
Show Gist options
  • Save asux/4a71c66c4ef6f15d6ab757e11bf66f23 to your computer and use it in GitHub Desktop.
Save asux/4a71c66c4ef6f15d6ab757e11bf66f23 to your computer and use it in GitHub Desktop.
SortCollection original
# frozen_string_literal: true
module Bl
module Core
module Logic
class SortCollection
include Dry::Monads::Result::Mixin
ALLOWED_ORDER_BY = %i[created_at updated_at rating votes_count last_activity_date answers_count].freeze
ALLOWED_ORDER_DIRS = %i[asc desc].freeze
Schema = Dry::Validation.Schema do
configure do
predicates(Bl::Core::Logic::ActiveRecordPredicates)
end
required(:collection).filled(:orderable?)
end
OptionsSchema = Dry::Validation.Schema do
required(:order_by).value(included_in?: ALLOWED_ORDER_BY)
required(:order_dir).value(included_in?: ALLOWED_ORDER_DIRS)
end
def call(input, options = {})
return Success(input) if options.blank?
validation = OptionsSchema.call(options)
return Failure(input.merge(errors: validation.errors)) if validation.failure?
validation = Schema.call(input)
return Failure(input.merge(errors: validation.errors)) if validation.failure?
collection = input[:collection]
sorted = collection.order(options[:order_by] => options[:order_dir])
input[:collection] = sorted
Success(input)
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment