Class: Babik::QuerySet::OrderField

Inherits:
Object
  • Object
show all
Defined in:
lib/babik/queryset/components/order.rb

Overview

Each one of the fields that appear in the order statement

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model, field_path, direction) ⇒ OrderField

Construct the OrderField

Parameters:

  • model (ActiveRecord::Base)

    base model.

  • field_path (String, Symbol, Selection)

    field path. If local, it will be one of the attributes, otherwise will be an association path.

  • direction (String, Symbol)

    :ASC or :DESC (a string will be converted to symbol).



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/babik/queryset/components/order.rb', line 121

def initialize(model, field_path, direction)
  direction_sym = direction.to_sym
  unless %i[ASC DESC].include?(direction_sym)
    raise "Invalid order type #{direction} in #{field_path}: Expecting :ASC or :DESC"
  end
  @model = model
  if [String, Symbol].include?(field_path.class)
    @selection = Babik::Selection::Path::Factory.build(@model, field_path)
  elsif [Babik::Selection::Path::LocalPath, Babik::Selection::Path::ForeignPath].include?(field_path.class)
    @selection = field_path
  else
    raise "field_path of class #{field_path.class} not valid. A Symbol/String/Babik::Selection::Base expected"
  end
  @direction = direction_sym
end

Instance Attribute Details

#directionObject (readonly)

Returns the value of attribute direction.



112
113
114
# File 'lib/babik/queryset/components/order.rb', line 112

def direction
  @direction
end

#modelObject (readonly)

Returns the value of attribute model.



112
113
114
# File 'lib/babik/queryset/components/order.rb', line 112

def model
  @model
end

#selectionObject (readonly)

Returns the value of attribute selection.



112
113
114
# File 'lib/babik/queryset/components/order.rb', line 112

def selection
  @selection
end

Instance Method Details

#invertOrderField

Return a new OrderField with the direction inverted

Returns:

  • (OrderField)

    Order field with inverted direction.



139
140
141
142
143
144
145
146
# File 'lib/babik/queryset/components/order.rb', line 139

def invert
  inverted_direction = if @direction.to_sym == :ASC
                         :DESC
                       else
                         :ASC
                       end
  OrderField.new(@model, @selection, inverted_direction)
end

#sqlSQL

Return sql of the field to order. i.e. something like this:

<table_alias>.<field> ASC
<table_alias>.<field> DESC

e.g.

users_0.first_name ASC
posts_0.title DESC

Returns:

  • (SQL)

    SQL code for field to order.



156
157
158
# File 'lib/babik/queryset/components/order.rb', line 156

def sql
  "#{@selection.target_alias}.#{@selection.selected_field} #{@direction}"
end