Module: Querifier::Queries::Order

Defined in:
lib/querifier/queries/order.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(message, *args, &block) ⇒ Object



45
46
47
48
# File 'lib/querifier/queries/order.rb', line 45

def method_missing(message, *args, &block)
  return order_by(Regexp.last_match(1).to_sym, *args) if message.to_s =~ /order_by_(.*)/ # rubocop:disable Performance/RegexpMatch, Metrics/LineLength
  super
end

Class Method Details

.included(klass) ⇒ Object



55
56
57
# File 'lib/querifier/queries/order.rb', line 55

def self.included(klass)
  klass.extend(ClassMethods)
end

Instance Method Details

#collectionObject



4
5
6
7
8
# File 'lib/querifier/queries/order.rb', line 4

def collection
  super
  order
  @collection
end

#orderObject



10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/querifier/queries/order.rb', line 10

def order
  return self if @ordered
  if valid_sort?
    # TODO: Permit multiple orders
    option = order_params.keys.first
    direction = order_params.fetch(option, nil)
    send("order_by_#{option}", direction)
  else
    order_by_default
  end
  @ordered = true
  self
end

#order_by(option, direction) ⇒ Object



28
29
30
# File 'lib/querifier/queries/order.rb', line 28

def order_by(option, direction)
  @collection = @collection.order(option => direction)
end

#order_by_defaultObject



24
25
26
# File 'lib/querifier/queries/order.rb', line 24

def order_by_default
  order_by(*self.class.default_sort.to_a.flatten)
end

#order_paramsObject



50
51
52
53
# File 'lib/querifier/queries/order.rb', line 50

def order_params
  @order_params ||=
    params.fetch(Config.order_param, {}).select { |k| valid_option? k.to_sym }
end

#valid_option?(option) ⇒ Boolean

Returns:

  • (Boolean)


41
42
43
# File 'lib/querifier/queries/order.rb', line 41

def valid_option?(option)
  self.class.order_attributes.include?(option.to_sym)
end

#valid_sort?Boolean

Returns:

  • (Boolean)


32
33
34
35
36
37
38
39
# File 'lib/querifier/queries/order.rb', line 32

def valid_sort?
  option = order_params.keys.first
  direction = order_params.fetch(option, nil)
  option &&
    direction &&
    valid_option?(option) &&
    %w[asc desc].include?(direction.to_s.downcase)
end