Class: Rails::Hyperdrive::Tools::ListModels
- Inherits:
-
Base
- Object
- MCP::Tool
- Base
- Rails::Hyperdrive::Tools::ListModels
show all
- Defined in:
- lib/rails/hyperdrive/tools/list_models.rb
Class Method Summary
collapse
Methods inherited from Base
respond_error, respond_json, respond_text, with_dev_guard
Class Method Details
.call(server_context: nil) ⇒ Object
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
# File 'lib/rails/hyperdrive/tools/list_models.rb', line 12
def self.call(server_context: nil)
with_dev_guard do
::Rails.application.eager_load!
models = ActiveRecord::Base.descendants.reject(&:abstract_class?).sort_by(&:name)
described = models.map do |m|
describe(m)
rescue StandardError => e
{ class: m.name, errors: ["#{e.class}: #{e.message}"] }
end
respond_json(described)
end
end
|
.describe(model) ⇒ Object
27
28
29
30
31
32
33
34
35
|
# File 'lib/rails/hyperdrive/tools/list_models.rb', line 27
def self.describe(model)
{
class: model.name,
table: safe(model, :table_name),
columns: safe_columns(model),
validators: safe_validators(model),
associations: safe_associations(model)
}
end
|
.safe(model, method) ⇒ Object
37
38
39
40
41
|
# File 'lib/rails/hyperdrive/tools/list_models.rb', line 37
def self.safe(model, method)
model.public_send(method)
rescue => e
"<error: #{e.class}: #{e.message}>"
end
|
.safe_associations(model) ⇒ Object
60
61
62
63
64
65
66
|
# File 'lib/rails/hyperdrive/tools/list_models.rb', line 60
def self.safe_associations(model)
model.reflect_on_all_associations.map do |a|
{ name: a.name.to_s, macro: a.macro.to_s, class_name: safe_class_name(a) }
end
rescue
[]
end
|
.safe_class_name(association) ⇒ Object
68
69
70
71
72
|
# File 'lib/rails/hyperdrive/tools/list_models.rb', line 68
def self.safe_class_name(association)
association.class_name
rescue
nil
end
|
.safe_columns(model) ⇒ Object
43
44
45
46
47
48
|
# File 'lib/rails/hyperdrive/tools/list_models.rb', line 43
def self.safe_columns(model)
return [] unless model.connected? || ActiveRecord::Base.connected?
model.columns.map { |c| { name: c.name, type: c.type.to_s, null: c.null, default: c.default } }
rescue => e
[{ error: "#{e.class}: #{e.message}" }]
end
|
.safe_validators(model) ⇒ Object
50
51
52
53
54
55
56
57
58
|
# File 'lib/rails/hyperdrive/tools/list_models.rb', line 50
def self.safe_validators(model)
model.validators.flat_map do |v|
v.attributes.map do |attr|
{ attribute: attr.to_s, kind: v.kind.to_s, options: v.options.transform_values(&:to_s) }
end
end
rescue
[]
end
|