Skip to content

Instantly share code, notes, and snippets.

@tiegz
Created November 13, 2017 21:57
Show Gist options
  • Save tiegz/acfaa012c971b470af397b33589d5963 to your computer and use it in GitHub Desktop.
Save tiegz/acfaa012c971b470af397b33589d5963 to your computer and use it in GitHub Desktop.
CountLoader
# Param-based count loader (for params and foreign keys).
#
# Example:
# CountLoader.for(Category).load(category_id)
#
class CountLoader < GraphQL::Batch::Loader
def initialize(model, param: :id, scope: nil)
@model = model
@param = param
@scope = case scope
when Symbol
scope.to_proc
when Hash
->(mod) { mod.where(scope) }
when ActiveRecord::Relation
->(_) { scope }
end
end
def perform(ids)
scope = @scope ? @scope.call(@model) : @model
scope.where(@param => ids).group(@param).count
.each_pair { |record_id, count| fulfill(record_id.to_s, count) }
ids.each { |id|
id_ = id.to_s
fulfill(id_, nil) unless fulfilled?(id_)
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment