Class: Datagrid::Drivers::ActiveRecord

Inherits:
AbstractDriver show all
Defined in:
lib/datagrid/drivers/active_record.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from AbstractDriver

guess_driver, inherited, #match?, #reverse_order

Class Method Details

.match?(scope) ⇒ Boolean

Returns:

  • (Boolean)


5
6
7
8
9
10
11
12
# File 'lib/datagrid/drivers/active_record.rb', line 5

def self.match?(scope)
  return false unless defined?(::ActiveRecord)
  if scope.is_a?(Class) 
    scope.ancestors.include?(::ActiveRecord::Base)
  else
    scope.is_a?(::ActiveRecord::Relation) 
  end
end

Instance Method Details

#asc(scope, order) ⇒ Object



33
34
35
36
37
# File 'lib/datagrid/drivers/active_record.rb', line 33

def asc(scope, order)
  # Rails 3.x.x don't able to override already applied order
  # Using #reorder instead
  scope.reorder(order)
end

#default_order(scope, column_name) ⇒ Object



43
44
45
# File 'lib/datagrid/drivers/active_record.rb', line 43

def default_order(scope, column_name)
  has_column?(scope, column_name) ? [scope.table_name, column_name].join(".") : nil
end

#desc(scope, order) ⇒ Object



39
40
41
# File 'lib/datagrid/drivers/active_record.rb', line 39

def desc(scope, order)
  scope.reorder(order).reverse_order
end

#greater_equal(scope, field, value) ⇒ Object



47
48
49
# File 'lib/datagrid/drivers/active_record.rb', line 47

def greater_equal(scope, field, value)
  scope.where(["#{scope.table_name}.#{field} >= ?", value])
end

#has_column?(scope, column_name) ⇒ Boolean

Returns:

  • (Boolean)


55
56
57
58
59
# File 'lib/datagrid/drivers/active_record.rb', line 55

def has_column?(scope, column_name)
  scope.column_names.include?(column_name.to_s)
rescue ::ActiveRecord::StatementInvalid
  false
end

#less_equal(scope, field, value) ⇒ Object



51
52
53
# File 'lib/datagrid/drivers/active_record.rb', line 51

def less_equal(scope, field, value)
  scope.where(["#{scope.table_name}.#{field} <= ?", value])
end

#to_scope(scope) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/datagrid/drivers/active_record.rb', line 14

def to_scope(scope)
  return scope if scope.is_a?(::ActiveRecord::Relation)
  # Model class or Active record association
  # ActiveRecord association class hides itself under an Array 
  # We can only reveal it by checking if it respond to some specific
  # to ActiveRecord method like #scoped
  if scope.is_a?(Class) 
    scope.scoped({})
  elsif scope.respond_to?(:scoped)
    scope.scoped
  else
    scope
  end
end

#where(scope, attribute, value) ⇒ Object



29
30
31
# File 'lib/datagrid/drivers/active_record.rb', line 29

def where(scope, attribute, value)
  scope.where(attribute => value)
end