Module: Torque::PostgreSQL::Relation::Buckets

Defined in:
lib/torque/postgresql/relation/buckets.rb

Defined Under Namespace

Modules: Initializer

Instance Method Summary collapse

Instance Method Details

#buckets(*value, **xargs) ⇒ Object

Specifies how to bucket records. It works for both the calculations or just putting records into groups. For example:

User.buckets(:created_at, [1.year.ago, 1.month.ago, 1.week.ago])
# Returns all users grouped by created_at in the given time ranges

User.buckets(:age, 0..100, step: 10).count
# Counts all users grouped by age buckets of 10 years


26
27
28
# File 'lib/torque/postgresql/relation/buckets.rb', line 26

def buckets(*value, **xargs)
  spawn.buckets!(*value, **xargs)
end

#buckets!(attribute, values, count: nil, cast: nil, as: nil) ⇒ Object

Like #buckets, but modifies relation in place.

Raises:

  • (ArgumentError)


31
32
33
34
35
36
37
38
39
40
# File 'lib/torque/postgresql/relation/buckets.rb', line 31

def buckets!(attribute, values, count: nil, cast: nil, as: nil)
  raise ArgumentError, <<~MSG.squish if !values.is_a?(Array) && !values.is_a?(Range)
    Buckets must be an array or a range.
  MSG

  count ||= 1 if values.is_a?(Range)
  attribute = arel_table[attribute] unless ::Arel.arel_node?(attribute)
  self.buckets_value = [attribute, values, count, cast, as]
  self
end

#buckets_valueObject

:nodoc:



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

def buckets_value
  @values.fetch(:buckets, nil)
end

#buckets_value=(value) ⇒ Object

:nodoc:



13
14
15
16
# File 'lib/torque/postgresql/relation/buckets.rb', line 13

def buckets_value=(value)
  assert_modifiable!
  @values[:buckets] = value
end

#calculateObject

When performing calculations with buckets, this method add a grouping clause to the query by the bucket values, and then adjust the keys to match provided values

Raises:

  • (ArgumentError)


45
46
47
48
49
50
51
52
53
54
55
# File 'lib/torque/postgresql/relation/buckets.rb', line 45

def calculate(*)
  return super if buckets_value.blank?

  raise ArgumentError, <<~MSG.squish if group_values.present?
    Cannot calculate with buckets when there are already group values.
  MSG

  keys = buckets_keys
  self.group_values = [FN.group_by(build_buckets_node, :bucket)]
  super.transform_keys { |key| keys[key - 1] }
end