Class: Angsa::Base

Inherits:
Object
  • Object
show all
Includes:
Pagination, Searching, Sorting
Defined in:
lib/angsa/base.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Searching

#apply_search, #build_search_conditions_values_and_associations

Methods included from Sorting

#apply_sorting

Methods included from Pagination

#apply_pagination

Constructor Details

#initialize(params, model) ⇒ Base

Returns a new instance of Base.



14
15
16
17
# File 'lib/angsa/base.rb', line 14

def initialize(params, model)
  @params = params
  @model = model
end

Instance Attribute Details

#modelObject (readonly)

Returns the value of attribute model.



13
14
15
# File 'lib/angsa/base.rb', line 13

def model
  @model
end

#paramsObject (readonly)

Returns the value of attribute params.



13
14
15
# File 'lib/angsa/base.rb', line 13

def params
  @params
end

Instance Method Details

#as_jsonObject



53
54
55
56
57
58
# File 'lib/angsa/base.rb', line 53

def as_json(*)
  {
    total: total_count,
    data: data,
  }
end

#associationsObject



23
24
25
# File 'lib/angsa/base.rb', line 23

def associations
  columns.map { |column| column[:source].to_s.split('.').first if column[:source].to_s.include?('.') }.compact.uniq
end

#columnsObject

Raises:

  • (NotImplementedError)


19
20
21
# File 'lib/angsa/base.rb', line 19

def columns
  raise NotImplementedError, 'columns is not implemented in derived class'
end

#dataObject



33
34
35
36
37
38
# File 'lib/angsa/base.rb', line 33

def data
  records = data_model
  records = apply_sorting(records, params)
  records = apply_pagination(records, params)
  extract_records(records)
end

#data_modelObject



27
28
29
30
31
# File 'lib/angsa/base.rb', line 27

def data_model
  records = model.all
  records = records.includes(*associations) if associations.any?
  apply_search(records, params)
end

#extract_records(records) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/angsa/base.rb', line 40

def extract_records(records)
  records.map do |record|
    columns.map do |column|
      if column[:source].include?('custom_')
        [column[:name], send(column[:source], record)]
      else
        source = column[:source].split('.')
        [column[:name], source.size == 1 ? record.send(source.first) : record.send(source.first).send(source.last)]
      end
    end.to_h
  end
end


64
65
66
# File 'lib/angsa/base.rb', line 64

def print_columns
  puts columns
end

#total_countObject



60
61
62
# File 'lib/angsa/base.rb', line 60

def total_count
  data_model.count
end