rhino-rails 4.5.0 → 4.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: ecffad187ec69c47659219d1eb766247a82ce666a662be9a32c3d88afe4bd48c
4
- data.tar.gz: 1ccb038bc991c74d4338b84a20280b38660f1ec959552b3546625de855f37969
3
+ metadata.gz: 3c800a5e70d40849b886fdd638cc4214fa4bd782965de5a94394a6fa0319cb38
4
+ data.tar.gz: e967104d44d640b9645f579022f14831d36150e763497e25ecfbd2b391ec76b1
5
5
  SHA512:
6
- metadata.gz: 242a0d4672911f646bd9dc62dcfa6bd0641caed3ec88af8f62dea657f146e0d019f80d9cbe769fb9e7415c611e709946c1aeb01af4eeb1871ca590ea2533b866
7
- data.tar.gz: ea611e79054413e6322dd44a2a141aa01a0791a8eb48d13e4dd8311c03821c8195fb7befd598840d63401355a3fd4819f7b4506afd6486d38d5a0fedef48a5e4
6
+ metadata.gz: 717d3ad2ef05fe9ead1918baa1d52d61e865f0b3cd95925173df147ae41ba66786a88971eeed21ef5729103d07312c4b3fdb0ffd5ed2a398e140e3abeebca670
7
+ data.tar.gz: 0e20f9f6ee200c2643c691c4bac35a6acc6eb091103539b3271133c67f4093bae017bc5ce3b0955b2966ef1be1c688e30c4c17e28dd16566116e9beab5bee34e
data/README.md CHANGED
@@ -41,6 +41,7 @@ Register a model, get a full REST API instantly.
41
41
  | 27 | **Postman Export** | Auto-generated Postman Collection v2.1 with all endpoints. |
42
42
  | 28 | **Blueprint System** | YAML-to-code generation for models, migrations, factories, policies, tests, and seeders. |
43
43
  | 29 | **Named Scopes** | `?scope=availableForDrivers` client-selectable scopes (whitelisted via `rhino_scopes`), plus a `rhino_default_scope` applied when none is requested. Unknown scopes return 403. Applies to `index`/`trashed` only. |
44
+ | 30 | **Configurable Route Key** | Match the `:id` URL segment against any column (`rhino_route_key :hash_id` per model, or global `config.route_key`). Member endpoints only — payload FKs and nested-operation ids stay primary-key based. |
44
45
 
45
46
  ## Quick Start
46
47
 
@@ -96,7 +96,8 @@ module Rhino
96
96
  owner: options.fetch("owner", nil),
97
97
  except_actions: options.fetch("except_actions", []),
98
98
  pagination: options.fetch("pagination", false),
99
- per_page: options.fetch("per_page", 25)
99
+ per_page: options.fetch("per_page", 25),
100
+ route_key: options.fetch("route_key", nil)
100
101
  }
101
102
  end
102
103
 
@@ -65,7 +65,8 @@ module Rhino
65
65
  warnings.concat(perm_result[:warnings])
66
66
 
67
67
  # Options
68
- errors.concat(validate_options(blueprint[:options]))
68
+ errors.concat(validate_options(blueprint[:options], column_names))
69
+ warnings.concat(route_key_warnings(blueprint[:options], blueprint[:columns]))
69
70
 
70
71
  # Relationships
71
72
  errors.concat(validate_relationships(blueprint[:relationships]))
@@ -156,8 +157,9 @@ module Rhino
156
157
  { errors: errors, warnings: warnings }
157
158
  end
158
159
 
159
- # Validate options.
160
- def validate_options(options)
160
+ # Validate options. When +column_names+ is provided, also validates that
161
+ # a configured route_key references a declared column (or 'id').
162
+ def validate_options(options, column_names = nil)
161
163
  errors = []
162
164
 
163
165
  if options[:except_actions]
@@ -168,6 +170,11 @@ module Rhino
168
170
  end
169
171
  end
170
172
 
173
+ route_key = options[:route_key]
174
+ if route_key && column_names && !(["id"] + column_names).include?(route_key.to_s)
175
+ errors << "route_key '#{route_key}' does not match any declared column"
176
+ end
177
+
171
178
  errors
172
179
  end
173
180
 
@@ -193,6 +200,21 @@ module Rhino
193
200
  errors
194
201
  end
195
202
 
203
+ # Warn when the route_key column is not marked unique — non-unique route
204
+ # keys make member-endpoint lookups ambiguous.
205
+ def route_key_warnings(options, columns)
206
+ warnings = []
207
+ route_key = options[:route_key]
208
+ return warnings unless route_key
209
+
210
+ column = columns.find { |c| c[:name] == route_key.to_s }
211
+ if column && !column[:unique]
212
+ warnings << "route_key column '#{route_key}' is not marked unique — member lookups may be ambiguous"
213
+ end
214
+
215
+ warnings
216
+ end
217
+
196
218
  private
197
219
 
198
220
  def check_field_references(fields, column_names, role, field_key, warnings)
@@ -23,9 +23,12 @@ module Rhino
23
23
  slug = blueprint[:slug]
24
24
  permissions = blueprint[:permissions]
25
25
  columns = blueprint[:columns]
26
+ # URL segment attribute for member endpoints: the configured route
27
+ # key, or the primary key (id) when none is set.
28
+ route_key = (blueprint[:options] || {})[:route_key] || "id"
26
29
  factory_name = model_to_factory(model)
27
30
 
28
- role_contexts = build_role_contexts(slug, factory_name, permissions, columns, is_multi_tenant, org_identifier)
31
+ role_contexts = build_role_contexts(slug, factory_name, permissions, columns, is_multi_tenant, org_identifier, route_key)
29
32
 
30
33
  if is_multi_tenant
31
34
  wrap_multi_tenant(model, slug, role_contexts, org_identifier)
@@ -49,7 +52,7 @@ module Rhino
49
52
  model.gsub(/([a-z])([A-Z])/, '\1_\2').downcase
50
53
  end
51
54
 
52
- def build_role_contexts(slug, factory_name, permissions, columns, is_multi_tenant, org_identifier)
55
+ def build_role_contexts(slug, factory_name, permissions, columns, is_multi_tenant, org_identifier, route_key = "id")
53
56
  return "" if permissions.empty?
54
57
 
55
58
  all_defined_actions = permissions.values.flat_map { |p| p[:actions] }.uniq & ALL_ACTIONS
@@ -66,18 +69,18 @@ module Rhino
66
69
 
67
70
  # Individual allowed action tests
68
71
  allowed.each do |action|
69
- lines << build_single_action_test(slug, action, is_multi_tenant, org_identifier, true)
72
+ lines << build_single_action_test(slug, action, is_multi_tenant, org_identifier, true, route_key)
70
73
  lines << ""
71
74
  end
72
75
 
73
76
  # Individual blocked action tests
74
77
  blocked.each do |action|
75
- lines << build_single_action_test(slug, action, is_multi_tenant, org_identifier, false)
78
+ lines << build_single_action_test(slug, action, is_multi_tenant, org_identifier, false, route_key)
76
79
  lines << ""
77
80
  end
78
81
 
79
82
  # Field visibility tests
80
- field_test = build_field_visibility_test(slug, role, perm, columns, is_multi_tenant, org_identifier)
83
+ field_test = build_field_visibility_test(slug, role, perm, columns, is_multi_tenant, org_identifier, route_key)
81
84
  if field_test
82
85
  lines << field_test
83
86
  lines << ""
@@ -114,7 +117,7 @@ module Rhino
114
117
  end
115
118
  end
116
119
 
117
- def build_single_action_test(slug, action, is_multi_tenant, org_identifier, expect_success)
120
+ def build_single_action_test(slug, action, is_multi_tenant, org_identifier, expect_success, route_key = "id")
118
121
  id_actions = %w[show update destroy restore forceDelete]
119
122
  needs_id = id_actions.include?(action)
120
123
  needs_discard = %w[restore forceDelete].include?(action)
@@ -126,10 +129,10 @@ module Rhino
126
129
  }
127
130
 
128
131
  action_path_suffix = {
129
- "index" => "", "show" => "/\#{record.id}", "store" => "",
130
- "update" => "/\#{record.id}", "destroy" => "/\#{record.id}",
131
- "trashed" => "/trashed", "restore" => "/\#{record.id}/restore",
132
- "forceDelete" => "/\#{record.id}/force-delete"
132
+ "index" => "", "show" => "/\#{record.#{route_key}}", "store" => "",
133
+ "update" => "/\#{record.#{route_key}}", "destroy" => "/\#{record.#{route_key}}",
134
+ "trashed" => "/trashed", "restore" => "/\#{record.#{route_key}}/restore",
135
+ "forceDelete" => "/\#{record.#{route_key}}/force-delete"
133
136
  }
134
137
 
135
138
  success_codes = { "store" => ":created", "destroy" => ":no_content", "forceDelete" => ":no_content" }
@@ -168,7 +171,7 @@ module Rhino
168
171
  lines.join("\n")
169
172
  end
170
173
 
171
- def build_field_visibility_test(slug, role, perm, columns, is_multi_tenant, org_identifier)
174
+ def build_field_visibility_test(slug, role, perm, columns, is_multi_tenant, org_identifier, route_key = "id")
172
175
  return nil unless perm[:actions].include?("show")
173
176
  return nil if perm[:show_fields] == ["*"]
174
177
  return nil if perm[:show_fields].empty?
@@ -184,9 +187,9 @@ module Rhino
184
187
  lines << " it 'shows only permitted fields' do"
185
188
 
186
189
  if is_multi_tenant
187
- lines << " get \"/api/\#{org.#{org_identifier}}/#{slug}/\#{record.id}\", headers: auth_headers(user)"
190
+ lines << " get \"/api/\#{org.#{org_identifier}}/#{slug}/\#{record.#{route_key}}\", headers: auth_headers(user)"
188
191
  else
189
- lines << " get \"/api/#{slug}/\#{record.id}\", headers: auth_headers(user)"
192
+ lines << " get \"/api/#{slug}/\#{record.#{route_key}}\", headers: auth_headers(user)"
190
193
  end
191
194
 
192
195
  lines << " expect(response).to have_http_status(:ok)"
@@ -278,6 +278,7 @@ module Rhino
278
278
  content += " rhino_sorts #{sort_cols.map { |c| ":#{c}" }.join(', ')}\n" unless sort_cols.empty?
279
279
  content += " rhino_fields #{field_cols.map { |c| ":#{c}" }.join(', ')}\n" unless field_cols.empty?
280
280
  content += " rhino_includes #{include_cols.map { |c| ":#{c}" }.join(', ')}\n" unless include_cols.empty?
281
+ content += " rhino_route_key :#{blueprint[:options][:route_key]}\n" if blueprint[:options][:route_key]
281
282
 
282
283
  # Validations
283
284
 
@@ -20,6 +20,7 @@ module Rhino
20
20
  # rhino_middleware 'throttle:60,1'
21
21
  # rhino_middleware_actions store: ['verified'], update: ['verified']
22
22
  # rhino_except_actions :destroy
23
+ # rhino_route_key :hash_id
23
24
  # end
24
25
  module HasRhino
25
26
  extend ActiveSupport::Concern
@@ -39,6 +40,7 @@ module Rhino
39
40
  class_attribute :rhino_middleware_actions_map, default: {}
40
41
  class_attribute :rhino_except_actions_list, default: []
41
42
  class_attribute :rhino_owner_path, default: nil
43
+ class_attribute :rhino_route_key_column, default: nil
42
44
  end
43
45
 
44
46
  class_methods do
@@ -103,6 +105,36 @@ module Rhino
103
105
  self.rhino_except_actions_list = actions.map(&:to_s)
104
106
  end
105
107
 
108
+ # Column matched against the :id URL segment on member endpoints
109
+ # (show/update/destroy/restore/force_delete).
110
+ # rhino_route_key :hash_id # GET /api/jobs/{hash_id}
111
+ # Affects ONLY the URL-segment lookup — FK values in payloads, nested
112
+ # operation ids and audit references stay primary-key based.
113
+ def rhino_route_key(column)
114
+ self.rhino_route_key_column = column.to_s
115
+ end
116
+
117
+ # Resolve the effective route key for this model. Precedence:
118
+ # model-level +rhino_route_key+ → global +Rhino.config.route_key+ →
119
+ # primary key. O(1): class_attribute + config read; the column presence
120
+ # check uses ActiveRecord's cached +column_names+ (no queries).
121
+ #
122
+ # Raises ArgumentError when a configured key names a column that does
123
+ # not exist on the model — a clear failure instead of a silent 404.
124
+ def rhino_resolved_route_key
125
+ key = rhino_route_key_column.presence || Rhino.config.route_key.presence || primary_key
126
+ key = key.to_s
127
+
128
+ if key != primary_key.to_s && !column_names.include?(key)
129
+ raise ArgumentError,
130
+ "Invalid route key for #{name}: column '#{key}' does not exist on table " \
131
+ "'#{table_name}'. Check `rhino_route_key` on the model or the global " \
132
+ "`Rhino.config.route_key` setting."
133
+ end
134
+
135
+ key
136
+ end
137
+
106
138
  # Check if model uses soft deletes (Discard gem)
107
139
  def uses_soft_deletes?
108
140
  column_names.include?("discarded_at") || column_names.include?("deleted_at")
@@ -103,6 +103,10 @@ module Rhino
103
103
  if permitted && permitted != ['*']
104
104
  permitted_set = Set.new(permitted.map(&:to_s))
105
105
  permitted_set.add('id') # id is always allowed
106
+ # The route key column is always allowed too — responses must stay
107
+ # routable even when a policy whitelist omits it.
108
+ route_key = self.class.try(:rhino_resolved_route_key)
109
+ permitted_set.add(route_key.to_s) if route_key
106
110
  result.select! { |key, _| permitted_set.include?(key) }
107
111
  end
108
112
 
@@ -168,6 +172,13 @@ module Rhino
168
172
  if permitted != ['*']
169
173
  all_columns = self.class.column_names
170
174
  not_permitted = all_columns - permitted.map(&:to_s)
175
+ # A configured route key is never hidden by a policy whitelist —
176
+ # responses must stay routable. Default path (route key == primary
177
+ # key) is intentionally untouched for backward compatibility.
178
+ route_key = self.class.try(:rhino_resolved_route_key)
179
+ if route_key && route_key.to_s != self.class.primary_key.to_s
180
+ not_permitted -= [route_key.to_s]
181
+ end
171
182
  hidden.concat(not_permitted)
172
183
  end
173
184
  end
@@ -4,6 +4,11 @@ module Rhino
4
4
  class Configuration
5
5
  attr_accessor :models, :route_groups, :multi_tenant, :invitations, :nested, :test_framework,
6
6
  :client_path, :mobile_path
7
+ # Global default route key: the column matched against the :id URL segment
8
+ # on member endpoints (show/update/destroy/restore/force_delete) for every
9
+ # model that does not declare its own +rhino_route_key+. Default nil =
10
+ # primary key (today's behavior, fully backward compatible).
11
+ attr_accessor :route_key
7
12
  attr_reader :auth
8
13
 
9
14
  def initialize
@@ -27,6 +32,7 @@ module Rhino
27
32
  @test_framework = "rspec"
28
33
  @client_path = nil
29
34
  @mobile_path = nil
35
+ @route_key = nil
30
36
  end
31
37
 
32
38
  # Auth configuration accessor. Merges supplied keys over defaults so a host
@@ -104,7 +104,8 @@ module Rhino
104
104
  return auth_response if auth_response
105
105
 
106
106
  builder = QueryBuilder.new(model_class, params: params)
107
- builder.instance_variable_set(:@scope, model_class.where(id: record.id))
107
+ # record is already resolved via the route key; re-query by primary key
108
+ builder.instance_variable_set(:@scope, model_class.where(model_class.primary_key => record.id))
108
109
  apply_organization_scope(builder)
109
110
  builder.build
110
111
  record = builder.to_scope.first!
@@ -192,7 +193,7 @@ module Rhino
192
193
 
193
194
  # POST /api/{slug}/:id/restore
194
195
  def restore
195
- record = model_class.discarded.find(params[:id])
196
+ record = find_by_route_key(model_class.discarded)
196
197
  authorize record, :restore?, policy_class: policy_for(record)
197
198
 
198
199
  record.undiscard!
@@ -203,7 +204,7 @@ module Rhino
203
204
 
204
205
  # DELETE /api/{slug}/:id/force-delete
205
206
  def force_delete
206
- record = model_class.discarded.find(params[:id])
207
+ record = find_by_route_key(model_class.discarded)
207
208
  authorize record, :force_delete?, policy_class: policy_for(record)
208
209
 
209
210
  record.destroy!
@@ -493,7 +494,32 @@ module Rhino
493
494
  scope = scope.where(organization_id: org.id)
494
495
  end
495
496
 
496
- scope.find(params[:id])
497
+ find_by_route_key(scope)
498
+ end
499
+
500
+ # Column matched against the :id URL segment. Resolution chain:
501
+ # model's rhino_route_key → Rhino.config.route_key → primary key.
502
+ # O(1) — class_attribute + config read, no queries.
503
+ def route_key_for(model_class)
504
+ if model_class.respond_to?(:rhino_resolved_route_key)
505
+ model_class.rhino_resolved_route_key
506
+ else
507
+ model_class.primary_key
508
+ end
509
+ end
510
+
511
+ # Look up params[:id] within +scope+ using the resolved route key.
512
+ # Default path (route key == primary key) uses .find — byte-identical to
513
+ # the historical behavior. Configured path uses .find_by!, which raises
514
+ # ActiveRecord::RecordNotFound with the same 404 semantics.
515
+ def find_by_route_key(scope)
516
+ key = route_key_for(model_class)
517
+
518
+ if key.to_s == model_class.primary_key.to_s
519
+ scope.find(params[:id])
520
+ else
521
+ scope.find_by!(key => params[:id])
522
+ end
497
523
  end
498
524
 
499
525
  # ------------------------------------------------------------------
@@ -293,6 +293,30 @@ module Rhino
293
293
  # rhino_except_actions :store, :update, :destroy
294
294
  self.rhino_except_actions_list = []
295
295
 
296
+ # =========================================================================
297
+ # ROUTE KEY
298
+ # =========================================================================
299
+
300
+ # @!attribute [rw] rhino_route_key_column
301
+ # Column matched against the +:id+ URL segment on member endpoints
302
+ # (show, update, destroy, restore, force-delete).
303
+ #
304
+ # Default +nil+ = fall back to the global +Rhino.config.route_key+, then
305
+ # the primary key (today's behavior). Affects ONLY the URL-segment
306
+ # lookup — foreign keys in payloads, nested-operation ids and audit
307
+ # references stay primary-key based.
308
+ #
309
+ # Set via DSL: +rhino_route_key :hash_id+
310
+ #
311
+ # Query: +GET /api/jobs/{hash_id}+
312
+ #
313
+ # @return [String, nil]
314
+ # @example
315
+ # rhino_route_key :hash_id
316
+ # @example Direct assignment
317
+ # self.rhino_route_key_column = 'hash_id'
318
+ self.rhino_route_key_column = nil
319
+
296
320
  # =========================================================================
297
321
  # OWNERSHIP / MULTI-TENANCY
298
322
  # =========================================================================
@@ -232,6 +232,12 @@ module Rhino
232
232
  if valid_fields.any?
233
233
  # Always include the primary key
234
234
  valid_fields.unshift(model_class.primary_key) unless valid_fields.include?(model_class.primary_key)
235
+ # Also include the configured route key — sparse responses must stay
236
+ # routable. No-op in the default path (route key == primary key).
237
+ route_key = model_class.try(:rhino_resolved_route_key)
238
+ if route_key && route_key.to_s != model_class.primary_key.to_s && !valid_fields.include?(route_key.to_s)
239
+ valid_fields << route_key.to_s
240
+ end
235
241
  @scope = @scope.select(valid_fields.map { |f| "#{model_class.table_name}.#{f}" })
236
242
  end
237
243
  end
@@ -27,6 +27,8 @@ class <%= name %> < Rhino::RhinoModel
27
27
  <% unless include_cols.empty? -%>
28
28
  rhino_includes <%= include_cols.map { |c| ":#{c}" }.join(", ") %>
29
29
  <% end -%>
30
+ # Match the :id URL segment against another column (default: primary key):
31
+ # rhino_route_key :hash_id
30
32
 
31
33
  # ---------------------------------------------------------------
32
34
  # Validation (ActiveModel — use allow_nil: true for all validators)
@@ -79,6 +79,17 @@ Rhino.configure do |config|
79
79
  # Permissions then resolve from that matching membership row.
80
80
  # config.auth = { enforce_group_membership: false }
81
81
 
82
+ # ---------------------------------------------------------------
83
+ # Route Key
84
+ # ---------------------------------------------------------------
85
+ # Global default for which column matches the :id URL segment on member
86
+ # endpoints (show, update, destroy, restore, force-delete). Default nil =
87
+ # primary key. Individual models can override with `rhino_route_key :column`.
88
+ # Affects only URL lookups — foreign keys in payloads and nested-operation
89
+ # ids stay primary-key based.
90
+ #
91
+ # config.route_key = 'hash_id' # GET /api/jobs/{hash_id}
92
+
82
93
  # ---------------------------------------------------------------
83
94
  # Invitations
84
95
  # ---------------------------------------------------------------
@@ -66,6 +66,15 @@ class RhinoModel < Rhino::RhinoModel
66
66
  # rhino_includes :user, :comments, :tags
67
67
  # rhino_search :title, :content, :excerpt
68
68
 
69
+ # -----------------------------------------------------------------
70
+ # Route Key
71
+ # -----------------------------------------------------------------
72
+ #
73
+ # Match the :id URL segment against a column other than the primary key
74
+ # on member endpoints (show/update/destroy/restore/force-delete):
75
+ #
76
+ # rhino_route_key :hash_id # GET /api/jobs/{hash_id}
77
+
69
78
  # -----------------------------------------------------------------
70
79
  # Pagination
71
80
  # -----------------------------------------------------------------
data/lib/rhino/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Rhino
4
- VERSION = "4.5.0"
4
+ VERSION = "4.6.0"
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: rhino-rails
3
3
  version: !ruby/object:Gem::Version
4
- version: 4.5.0
4
+ version: 4.6.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Bruno Cipolla