Sha256: a522d3b3fcd1f99e1388b229867211ae1eaf45e8c9a43736bdd6d7fca65424af

Contents?: true

Size: 799 Bytes

Versions: 8

Compression:

Stored size: 799 Bytes

Contents

# frozen_string_literal: true

module Decidim
  module ActionDelegator
    class VotesCountAggregation
      def initialize(field, aliaz)
        @field = field
        @aliaz = aliaz
      end

      def to_sql
        int_field = cast(field, :integer)
        int_field = coalesce(int_field, 1)
        Arel::Nodes::Sum.new([int_field], aliaz).to_sql
      end

      private

      attr_reader :field, :aliaz

      # Returns the equivalent of `CAST ((<exprs>) AS <type>)` in Arel
      def cast(*exprs, type)
        Arel::Nodes::NamedFunction.new(
          "CAST",
          [Arel::Nodes::As.new(Arel::Nodes::Grouping.new(exprs), Arel.sql(type.to_s.upcase))]
        )
      end

      def coalesce(*exprs)
        Arel::Nodes::NamedFunction.new("COALESCE", exprs)
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
decidim-action_delegator-0.8.1 app/queries/decidim/action_delegator/votes_count_aggregation.rb
decidim-action_delegator-0.7.2 app/queries/decidim/action_delegator/votes_count_aggregation.rb
decidim-action_delegator-0.7.1 app/queries/decidim/action_delegator/votes_count_aggregation.rb
decidim-action_delegator-0.7.0 app/queries/decidim/action_delegator/votes_count_aggregation.rb
decidim-action_delegator-0.6.0 app/queries/decidim/action_delegator/votes_count_aggregation.rb
decidim-action_delegator-0.5.0 app/queries/decidim/action_delegator/votes_count_aggregation.rb
decidim-action_delegator-0.4.1 app/queries/decidim/action_delegator/votes_count_aggregation.rb
decidim-action_delegator-0.4 app/queries/decidim/action_delegator/votes_count_aggregation.rb