Class: CursorPager::OrderValue

Inherits:
Object
  • Object
show all
Defined in:
lib/cursor_pager/order_value.rb

Overview

Wraps ActiveRecord’s order values. Depending on how the order of the relation is defined, ActiveRecord will give you multiple arel nodes or just one string. This deals with the differences so we don’t have to do it anywhere else.

Constant Summary collapse

PARENTHESIS_REGEX =
/[\(\)]/.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(relation, attribute, direction = :asc) ⇒ OrderValue

Returns a new instance of OrderValue.



27
28
29
30
31
# File 'lib/cursor_pager/order_value.rb', line 27

def initialize(relation, attribute, direction = :asc)
  @relation = relation
  @attribute = attribute
  @direction = direction.downcase.to_sym
end

Instance Attribute Details

#attributeObject (readonly)

Returns the value of attribute attribute.



11
12
13
# File 'lib/cursor_pager/order_value.rb', line 11

def attribute
  @attribute
end

#directionObject (readonly)

Returns the value of attribute direction.



11
12
13
# File 'lib/cursor_pager/order_value.rb', line 11

def direction
  @direction
end

Class Method Details

.from_arel_node(relation, node) ⇒ Object



13
14
15
# File 'lib/cursor_pager/order_value.rb', line 13

def self.from_arel_node(relation, node)
  new(relation, node.value.name, node.direction)
end

.from_order_string(relation, value) ⇒ Object



17
18
19
20
21
22
23
24
25
# File 'lib/cursor_pager/order_value.rb', line 17

def self.from_order_string(relation, value)
  if value.match?(PARENTHESIS_REGEX)
    raise OrderValueError, "Order values can't include functions."
  end

  value.split(",").map do |split_value|
    new(relation, *split_value.squish.split)
  end
end

Instance Method Details

#order_stringObject



55
56
57
# File 'lib/cursor_pager/order_value.rb', line 55

def order_string
  "#{prefixed_attribute} #{direction}"
end

#prefixed_attributeObject



41
42
43
44
45
# File 'lib/cursor_pager/order_value.rb', line 41

def prefixed_attribute
  return attribute if attribute.include?(".")

  "#{relation.table_name}.#{attribute}"
end

#primary_key?Boolean

Returns:

  • (Boolean)


33
34
35
# File 'lib/cursor_pager/order_value.rb', line 33

def primary_key?
  relation.primary_key == attribute
end

#select_aliasObject



47
48
49
# File 'lib/cursor_pager/order_value.rb', line 47

def select_alias
  prefixed_attribute.tr(".", "_")
end

#select_stringObject



51
52
53
# File 'lib/cursor_pager/order_value.rb', line 51

def select_string
  "#{prefixed_attribute} AS #{select_alias}"
end

#typeObject



37
38
39
# File 'lib/cursor_pager/order_value.rb', line 37

def type
  relation.type_for_attribute(attribute).type
end