Skip to content

Commit

Permalink
Better way of handling model based counters
Browse files Browse the repository at this point in the history
  • Loading branch information
Michaelvilleneuve committed Dec 11, 2023
1 parent 5f99005 commit 0a987de
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions lib/statisfy/model.rb
Expand Up @@ -11,24 +11,25 @@ def self.included(klass)

module ClassMethods
def count(params)
a_bloc = params.fetch(:scopes, nil) || params.fetch(:uniq_by, nil) || params.fetch(:if, nil)
source = a_bloc&.source
raise ArgumentError, "Missing :as parameter" unless params[:as]

class_name = params[:as].to_s.camelize

eval <<-RUBY, binding, __FILE__, __LINE__ + 1
class ::Statisfy::#{class_name}
include Statisfy::Counter
#{source || "count(#{params})"}
end
RUBY

class_eval <<-RUBY, __FILE__, __LINE__ + 1
def self.#{params[:as]}
::Statisfy::#{class_name}
end
RUBY

"::Statisfy::#{class_name}".constantize.send(__method__, **params)
end
alias aggregate count
end
end
end

0 comments on commit 0a987de

Please sign in to comment.