Class: Tabulatr::Adapter

Inherits:
Object show all
Defined in:
lib/tabulatr/tabulatr/adapter.rb

Direct Known Subclasses

ActiveRecordAdapter, MongoidAdapter

Defined Under Namespace

Classes: ActiveRecordAdapter, MongoidAdapter

Instance Method Summary collapse

Constructor Details

#initialize(klaz) ⇒ Adapter

Returns a new instance of Adapter.



2
3
4
5
# File 'lib/tabulatr/tabulatr/adapter.rb', line 2

def initialize(klaz)
  @base = klaz
  @relation = klaz
end

Instance Method Details

#class_to_paramObject



13
14
15
# File 'lib/tabulatr/tabulatr/adapter.rb', line 13

def class_to_param
  @relation.to_s.downcase.gsub("/","_")
end

#order(sortparam, default) ⇒ Object



21
22
23
24
# File 'lib/tabulatr/tabulatr/adapter.rb', line 21

def order(sortparam, default)
  order_by, order_direction = sort_params(sortparam, default)
  order_by ? { :by => order_by, :direction => order_direction } : nil
end

#preconditions_scope(opts) ⇒ Object



17
18
19
# File 'lib/tabulatr/tabulatr/adapter.rb', line 17

def preconditions_scope(opts)
  opts[:precondition].present? ? @base.where(opts[:precondition]) : @base
end

#sort_params(sortparam, default) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/tabulatr/tabulatr/adapter.rb', line 26

def sort_params(sortparam, default)
  if sortparam
    if sortparam[:_resort]
      order_by = sortparam[:_resort].first.first
      order_direction = sortparam[:_resort].first.last.first.first
    else
      order_by = sortparam.first.first
      order_direction = sortparam.first.last.first.first
    end
    raise "SECURITY violation, sort field name is '#{n}'" unless /^[\w]+$/.match order_direction
    raise "SECURITY violation, sort field name is '#{n}'" unless /^[\d\w]+$/.match order_by
  else
    if default
      l = default.split(" ")
      raise(":default_order parameter should be of the form 'id asc' or 'name desc'.") if l.length == 0 or l.length > 2

      order_by = l[0]
      order_direction = l[1] || 'asc'
    else
      order_by = order_direction = nil
    end
  end

  return order_by, order_direction
end

#to_sqlObject



9
10
11
# File 'lib/tabulatr/tabulatr/adapter.rb', line 9

def to_sql
  @relation.to_sql if @relation.respond_to? :to_sql
end