Class: TinyAdmin::Plugins::ActiveRecordRepository
Constant Summary
BaseRepository::RecordNotFound
Instance Attribute Summary
#model
Instance Method Summary
collapse
#initialize
Instance Method Details
#apply_filters(query, filters) ⇒ Object
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
# File 'lib/tiny_admin/plugins/active_record_repository.rb', line 54
def apply_filters(query, filters)
filters.each do |field, filter|
value = filter&.dig(:value)
next if value.nil? || value == ''
query =
case field.type
when :string
value = ActiveRecord::Base.sanitize_sql_like(value.strip)
query.where("#{field.name} LIKE ?", "%#{value}%")
else
query.where(field.name => value)
end
end
query
end
|
#collection ⇒ Object
42
43
44
|
# File 'lib/tiny_admin/plugins/active_record_repository.rb', line 42
def collection
model.all
end
|
#fields(options: nil) ⇒ Object
17
18
19
20
21
22
23
24
25
26
27
28
|
# File 'lib/tiny_admin/plugins/active_record_repository.rb', line 17
def fields(options: nil)
if options
types = model.columns.to_h { [_1.name, _1.type] }
options.to_h do |name, field_options|
[name, TinyAdmin::Field.create_field(name: name, type: types[name], options: field_options)]
end
else
model.columns.to_h do |column|
[column.name, TinyAdmin::Field.create_field(name: column.name, type: column.type)]
end
end
end
|
#find(reference) ⇒ Object
36
37
38
39
40
|
# File 'lib/tiny_admin/plugins/active_record_repository.rb', line 36
def find(reference)
model.find(reference)
rescue ActiveRecord::RecordNotFound => e
raise BaseRepository::RecordNotFound, e.message
end
|
#index_record_attrs(record, fields: nil) ⇒ Object
Also known as:
show_record_attrs
6
7
8
9
10
|
# File 'lib/tiny_admin/plugins/active_record_repository.rb', line 6
def index_record_attrs(record, fields: nil)
return record.attributes.transform_values(&:to_s) unless fields
fields.to_h { [_1, record.send(_1)] }
end
|
#index_title ⇒ Object
12
13
14
15
|
# File 'lib/tiny_admin/plugins/active_record_repository.rb', line 12
def index_title
title = model.to_s
title.respond_to?(:pluralize) ? title.pluralize : title
end
|
#list(page: 1, limit: 10, sort: nil, filters: nil) ⇒ Object
46
47
48
49
50
51
52
|
# File 'lib/tiny_admin/plugins/active_record_repository.rb', line 46
def list(page: 1, limit: 10, sort: nil, filters: nil)
query = sort ? collection.order(sort) : collection
query = apply_filters(query, filters) if filters
page_offset = page.positive? ? (page - 1) * limit : 0
records = query.offset(page_offset).limit(limit).to_a
[records, query.count]
end
|
#show_title(record) ⇒ Object
32
33
34
|
# File 'lib/tiny_admin/plugins/active_record_repository.rb', line 32
def show_title(record)
"#{model} ##{record.id}"
end
|