Method: OrderQuery::Column#initialize

Defined in:
lib/order_query/column.rb

#initialize(scope, attr_name, *vals_and_or_dir, unique: nil, nulls: false, sql: nil) ⇒ Column

Returns a new instance of Column.

Parameters:

  • scope (ActiveRecord::Relation)
  • attr_name (Symbol)

    the name of the column, or the method providing the value to sort by.

  • vals_and_or_dir (Array)

    optionally, values in the desired order, and / or one of ‘:asc`, `:desc`. Default order is `:desc` if the values are given (so the result is ordered like the values), `:asc` otherwise.

  • unique (Boolean) (defaults to: nil)

    mark the attribute as unique to avoid redundant columns. Default: ‘true` for primary key.

  • nulls (:first, :last, false) (defaults to: false)

    whether to consider NULLS to be ordered first or last. If false, assumes that a column is not nullable and raises [Errors::NonNullableColumnIsNullError] if a null is encountered.

  • sql (String, nil) (defaults to: nil)

    a custom sql fragment.



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/order_query/column.rb', line 29

def initialize(scope, attr_name, *vals_and_or_dir,
               unique: nil, nulls: false, sql: nil)
  @name = attr_name
  @order_enum = vals_and_or_dir.shift if vals_and_or_dir[0].is_a?(Array)
  @direction = Direction.parse!(
    vals_and_or_dir.shift || (@order_enum ? :desc : :asc)
  )
  unless vals_and_or_dir.empty?
    fail ArgumentError,
         "extra arguments: #{vals_and_or_dir.map(&:inspect) * ', '}"
  end
  @unique = unique.nil? ? (name.to_s == scope.primary_key) : unique
  if @order_enum&.include?(nil)
    fail ArgumentError, '`nulls` cannot be set if a value is null' if nulls

    @nullable = true
    @nulls = if @order_enum[0].nil?
               @direction == :desc ? :first : :last
             else
               @direction == :desc ? :last : :first
             end
  else
    @nullable = !!nulls # rubocop:disable Style/DoubleNegation
    @nulls = NullsDirection.parse!(
      nulls || NullsDirection.default(scope, @direction)
    )
  end
  @custom_sql = sql
  @sql_builder = SQL::Column.new(scope, self)
end