Module: Torque::PostgreSQL::Relation::Segments

Included in:
ActiveRecord::Relation
Defined in:
lib/torque/postgresql/relation/segments.rb,
sig/torque/postgresql/relation/segments.rbs

Instance Method Summary collapse

Instance Method Details

#segments(**map) ⇒ relation

Maps names to conditions so that the next calculation returns one value per name, each aggregate filtered by its condition. Anything that can become a relation is accepted as a condition, an array applies each of its items in order, and nil means the aggregate is not filtered at all. For example:

User.segments(all: nil, adults: { age: 18.. }).count
# Returns { all: 15, adults: 12 }

User.group(:role).segments(adults: { age: 18.. }).sum(:age)
# Returns { 'visitor' => { adults: 480 }, ... }

Parameters:

  • map (condition)

Returns:

  • (relation)


30
31
32
# File 'lib/torque/postgresql/relation/segments.rb', line 30

def segments(**map)
  spawn.segments!(**map)
end

#segments!(**map) ⇒ self

Like #segments, but modifies relation in place.

Parameters:

  • map (condition)

Returns:

  • (self)


35
36
37
38
39
# File 'lib/torque/postgresql/relation/segments.rb', line 35

def segments!(**map)
  predicates = map.to_h { |name, condition| [name, segment_predicate_for(name, condition)] }
  self.segments_value = segments_value.merge(predicates)
  self
end

#segments_value ⇒ Hash[Symbol, arel_node?]

:nodoc:

Returns:

  • (Hash[Symbol, arel_node?])


9
10
11
# File 'lib/torque/postgresql/relation/segments.rb', line 9

def segments_value
  @values.fetch(:segments, ::ActiveRecord::QueryMethods::FROZEN_EMPTY_HASH)
end

#segments_value=(value) ⇒ Hash[Symbol, arel_node?]

:nodoc:

Parameters:

  • value (Hash[Symbol, arel_node?])

Returns:

  • (Hash[Symbol, arel_node?])


14
15
16
17
# File 'lib/torque/postgresql/relation/segments.rb', line 14

def segments_value=(value)
  assert_modifiable!
  @values[:segments] = value
end