resteze 1.0.0 → 1.1.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.
@@ -45,14 +45,16 @@ module Resteze
45
45
  {}
46
46
  end
47
47
 
48
- def invoke_action(name, params = {}, id: nil)
48
+ # path_params and parent are the path context of a class that declares
49
+ # a path_template; they route the request and are handed to any of
50
+ # this class's objects in the result. Other classes are never passed
51
+ # them.
52
+ def invoke_action(name, params = {}, id: nil, path_params: {}, parent: nil)
49
53
  action = action_for(name)
50
54
  raise_invalid_action_id!(id) if action.member? && id.blank?
51
55
 
52
- params = action_params(name, params)
53
- params = { action.id_param => id }.merge(params) if action.member? && action.id == :param
54
- response = request(action.http_method, action.path_for(id), params:, headers: action_headers(name, params))
55
- build_action_result(action, response)
56
+ response = request_action(action, action_params(name, params), id, path_params)
57
+ apply_path_context(build_action_result(action, response), path_params, parent)
56
58
  end
57
59
 
58
60
  private
@@ -102,14 +104,36 @@ module Resteze
102
104
  end
103
105
  end
104
106
 
107
+ def request_action(action, params, id, path_params)
108
+ params = { action.id_param => id }.merge(params) if action.member? && action.id == :param
109
+ request(action.http_method, action.path_for(id, path_params), params:,
110
+ headers: action_headers(action.name, params))
111
+ end
112
+
105
113
  def define_action_methods(action)
114
+ action.member? ? define_member_action(action) : define_collection_action(action)
115
+ end
116
+
117
+ # The instance form routes with the instance's own path context, so
118
+ # every keyword is a request param; the class form takes path context
119
+ # from its keywords.
120
+ def define_member_action(action)
106
121
  name = action.name
107
122
  method_name = action.generated_name
108
- if action.member?
109
- define_method(method_name) { |**params| self.class.invoke_action(name, params, id:) }
110
- define_singleton_method(method_name) { |id, **params| new(id).public_send(method_name, **params) }
111
- else
112
- define_singleton_method(method_name) { |**params| invoke_action(name, params) }
123
+ define_method(method_name) do |**params|
124
+ self.class.invoke_action(name, params, id:, **action_path_context)
125
+ end
126
+ define_singleton_method(method_name) do |id, **params|
127
+ path_params, parent, params = partition_path_keywords(params)
128
+ new(id).assign_path_context(path_params, parent).public_send(method_name, **params)
129
+ end
130
+ end
131
+
132
+ def define_collection_action(action)
133
+ name = action.name
134
+ define_singleton_method(action.generated_name) do |**params|
135
+ path_params, parent, params = partition_path_keywords(params)
136
+ invoke_action(name, params, **action_path_context(path_params, parent))
113
137
  end
114
138
  end
115
139
  end
@@ -3,11 +3,15 @@ module Resteze
3
3
  extend ActiveSupport::Concern
4
4
  include Resteze::Request
5
5
  include Resteze::Actions
6
+ include Resteze::PathTemplate
6
7
 
7
- def initialize(id = nil, values: {})
8
+ # Keywords other than values: are path context, accepted only by a class
9
+ # that declares a path_template: its tokens, and parent:.
10
+ def initialize(id = nil, values: {}, **path_context)
8
11
  super(values)
9
12
  id, @retrieve_params = util.normalize_id(id)
10
13
  self.id = id if self.class.property?(:id)
14
+ assign_path_context(*self.class.path_context!(path_context))
11
15
  end
12
16
 
13
17
  def resource_path
@@ -16,7 +20,7 @@ module Resteze
16
20
  "invalid ID: #{id.inspect}", "id")
17
21
  end
18
22
 
19
- self.class.resource_path(id)
23
+ self.class.resource_path(id, **routing_path_params)
20
24
  end
21
25
 
22
26
  # The path #refresh requests: the routed :retrieve action. Unlike
@@ -31,7 +35,7 @@ module Resteze
31
35
  "invalid ID: #{id.inspect}", "id")
32
36
  end
33
37
 
34
- retrieve_action.path_for(id)
38
+ retrieve_action.path_for(id, routing_path_params)
35
39
  end
36
40
 
37
41
  def retrieve_method
@@ -77,12 +81,27 @@ module Resteze
77
81
  api_module.default_resource_slug(self)
78
82
  end
79
83
 
80
- def resource_path(id = nil)
81
- api_path([resource_slug, id].compact.map { |part| CGI.escape(part.to_s) }.join("/".freeze))
84
+ # The slug, or the filled path_template, followed by the id. Path
85
+ # values are only accepted by a class that declares a path_template.
86
+ # An id that is blank, "." or ".." raises InvalidRequestError; pass no
87
+ # id for the collection path.
88
+ def resource_path(id = nil, **path_params)
89
+ encoded_id = Resteze::Util.encode_path_segment(path_value!(:id, id)) unless id.nil?
90
+ api_path([*resource_segments(path_params), encoded_id].compact.join("/".freeze))
82
91
  end
83
92
 
84
- def retrieve(id)
85
- new(id).refresh
93
+ # The id is positional, or the keywords themselves in the hash form
94
+ # (`retrieve(id: "abc", expand: true)`). A templated class takes its
95
+ # path values and parent: out of the keywords first.
96
+ def retrieve(id = nil, **keywords)
97
+ path_params, parent, rest = partition_path_keywords(keywords)
98
+ if id.nil?
99
+ id = rest
100
+ else
101
+ reject_unknown_keywords!(rest)
102
+ end
103
+
104
+ new(id).assign_path_context(path_params, parent).refresh
86
105
  end
87
106
  end
88
107
 
@@ -0,0 +1,68 @@
1
+ module Resteze
2
+ # Opt-in mixin that adds #destroy and .destroy(id), routed through the
3
+ # built-in :destroy action (DELETE /slug/:id unless re-routed).
4
+ module Destroy
5
+ extend ActiveSupport::Concern
6
+
7
+ def destroy
8
+ resp = request(
9
+ destroy_method,
10
+ destroy_resource_path,
11
+ params: destroy_params,
12
+ headers: destroy_headers
13
+ )
14
+ process_destroy_response(resp)
15
+ end
16
+
17
+ def destroy_method
18
+ destroy_action.http_method
19
+ end
20
+
21
+ # While :destroy keeps its REST default, an instance-level resource_path
22
+ # override is honored, as #refresh does for :retrieve.
23
+ def destroy_resource_path
24
+ return resource_path if destroy_action.rest_default?
25
+
26
+ raise_invalid_destroy_id! if id.blank?
27
+ destroy_action.path_for(id, routing_path_params)
28
+ end
29
+
30
+ # The id param when the :destroy action carries the id as a param rather
31
+ # than in the path; otherwise nothing.
32
+ def destroy_params
33
+ return {} unless destroy_action.id == :param
34
+
35
+ { destroy_action.id_param => id }
36
+ end
37
+
38
+ def destroy_headers
39
+ respond_to?(:retrieve_headers) ? retrieve_headers : {}
40
+ end
41
+
42
+ # Override to turn the response into something else. The default is a
43
+ # Result, which is empty for a 204.
44
+ def process_destroy_response(response)
45
+ api_module::Result.from_response(response)
46
+ end
47
+
48
+ module ClassMethods
49
+ # Keywords are path context, accepted only by a class that declares a
50
+ # path_template: its tokens, and parent:.
51
+ def destroy(id, **path_context)
52
+ new(id).assign_path_context(*path_context!(path_context)).destroy
53
+ end
54
+ end
55
+
56
+ private
57
+
58
+ def destroy_action
59
+ self.class.action_for(:destroy)
60
+ end
61
+
62
+ def raise_invalid_destroy_id!
63
+ raise api_module::InvalidRequestError.new(
64
+ "Could not determine which PATH to request: #{self.class} instance has invalid ID: #{id.inspect}", "id"
65
+ )
66
+ end
67
+ end
68
+ end
data/lib/resteze/list.rb CHANGED
@@ -4,9 +4,12 @@ module Resteze
4
4
  include ApiModule
5
5
 
6
6
  module ClassMethods
7
- def list(params: {})
8
- resp = request(list_method, list_resource_path(params), params: list_params(params))
9
- construct_list_from(resp.data)
7
+ # Keywords other than params: are path context, accepted only by a
8
+ # class that declares a path_template.
9
+ def list(params: {}, **path_context)
10
+ path_params, parent = path_context!(path_context)
11
+ resp = request(list_method, list_resource_path(params, **path_params), params: list_params(params))
12
+ apply_path_context(construct_list_from(resp.data), path_params, parent)
10
13
  end
11
14
 
12
15
  def construct_list_from(payload)
@@ -27,8 +30,8 @@ module Resteze
27
30
  {}
28
31
  end
29
32
 
30
- def list_resource_path(_params = {})
31
- action_for(:list).path_for
33
+ def list_resource_path(_params = {}, **path_params)
34
+ action_for(:list).path_for(nil, path_params)
32
35
  end
33
36
 
34
37
  def list_key
@@ -0,0 +1,208 @@
1
+ module Resteze
2
+ # Nested resources. `path_template "catalogs/:catalog_name/items"` on a
3
+ # resource replaces its slug with a path whose :tokens are filled per call:
4
+ # class methods take them as keywords (`Item.list(catalog_name: "shoes")`)
5
+ # and instances remember them, so every action routes under the parent.
6
+ # A `parent:` keyword rides along as a plain reference (`item.parent`).
7
+ module PathTemplate
8
+ extend ActiveSupport::Concern
9
+
10
+ RESERVED = %i[id params values parent].freeze
11
+ TOKEN = /\A:([a-z_][a-z0-9_]*)\z/
12
+
13
+ # Holds the generated readers. They sit behind the class's own methods,
14
+ # so a property of the same name keeps its reader whichever is declared
15
+ # first.
16
+ class Readers < Module; end
17
+
18
+ # The values that fill this instance's path: those it was given, falling
19
+ # back to a property of the same name (for an API that echoes the
20
+ # parent's id in the body).
21
+ def path_params
22
+ routing_path_params
23
+ end
24
+
25
+ def nested?
26
+ self.class.nested?
27
+ end
28
+
29
+ # The object handed over as `parent:`, if any. Never fetched or
30
+ # serialized. Also readable as #parent unless a property takes that name.
31
+ def path_parent
32
+ @path_parent
33
+ end
34
+
35
+ def assign_path_context(path_params, parent = nil)
36
+ @path_params = (path_params || {}).slice(*self.class.path_tokens)
37
+ @path_parent = parent
38
+ self
39
+ end
40
+
41
+ private
42
+
43
+ # What #path_params returns. Resteze routes with this, so a resource
44
+ # that names a property `path_params` still routes correctly.
45
+ def routing_path_params
46
+ given = @path_params || {}
47
+ self.class.path_tokens.to_h { |token| [token, given[token].presence || path_property(token)] }.compact.freeze
48
+ end
49
+
50
+ # The keywords that carry this instance's path context to invoke_action:
51
+ # none for a class with no template, so a 1.0.0 override still fits.
52
+ def action_path_context
53
+ self.class.action_path_context(routing_path_params, path_parent)
54
+ end
55
+
56
+ def path_property(token)
57
+ self[token].presence if self.class.property?(token)
58
+ end
59
+
60
+ module ClassMethods
61
+ # With a template, declares it; without, returns the one in effect.
62
+ def path_template(template = nil)
63
+ return declare_path_template(template.to_s) if template
64
+
65
+ @path_template || (superclass.path_template if superclass.respond_to?(:path_template))
66
+ end
67
+
68
+ # True for a resource that lives under a parent: one that declares
69
+ # (or inherits) a path_template.
70
+ def nested?
71
+ path_template.present?
72
+ end
73
+
74
+ # The template's token names, in order: the keywords this class's
75
+ # methods take as path values, and the keys of an instance's
76
+ # #path_params.
77
+ def path_tokens
78
+ path_template_segments.grep(Symbol)
79
+ end
80
+
81
+ # The template as literal Strings and token Symbols.
82
+ def path_template_segments
83
+ return @path_template_segments if @path_template
84
+
85
+ superclass.respond_to?(:path_template_segments) ? superclass.path_template_segments : []
86
+ end
87
+
88
+ # Splits keywords into [path values, parent, everything else]. A class
89
+ # with no template takes no path keywords, so all of them are "else".
90
+ def partition_path_keywords(keywords)
91
+ return [{}, nil, keywords] unless nested?
92
+
93
+ tokens = path_tokens
94
+ [keywords.slice(*tokens), keywords[:parent], keywords.except(*tokens, :parent)]
95
+ end
96
+
97
+ # As partition_path_keywords, for methods whose keywords are all path
98
+ # context: anything left over is an unknown keyword.
99
+ def path_context!(keywords)
100
+ path_params, parent, rest = partition_path_keywords(keywords)
101
+ reject_unknown_keywords!(rest)
102
+ [path_params, parent]
103
+ end
104
+
105
+ def reject_unknown_keywords!(keywords)
106
+ return if keywords.empty?
107
+
108
+ raise ArgumentError, "unknown keyword#{'s' if keywords.size > 1}: #{keywords.keys.map(&:inspect).join(', ')}"
109
+ end
110
+
111
+ def action_path_context(path_params, parent)
112
+ nested? ? { path_params:, parent: } : {}
113
+ end
114
+
115
+ # Gives objects this class built (one, or a list of them) the path
116
+ # values and parent of the call that produced them.
117
+ def apply_path_context(result, path_params, parent)
118
+ return result unless nested?
119
+
120
+ items = result.is_a?(::Array) ? result : [result]
121
+ items.each { |item| item.assign_path_context(path_params, parent) if item.is_a?(self) }
122
+ result
123
+ end
124
+
125
+ private
126
+
127
+ # The encoded path segments that precede the id.
128
+ def resource_segments(path_params)
129
+ reject_unknown_keywords!(path_params.except(*path_tokens))
130
+ return [Resteze::Util.encode_path_segment(resource_slug)] unless nested?
131
+
132
+ path_template_segments.map do |segment|
133
+ next segment unless segment.is_a?(Symbol)
134
+
135
+ Resteze::Util.encode_path_segment(path_value!(segment, path_params[segment]))
136
+ end
137
+ end
138
+
139
+ # A value that becomes a path segment, a token's or the id, must be
140
+ # present and must not be a dot segment.
141
+ def path_value!(token, value)
142
+ return value if value.present? && !Resteze::Util.dot_segment?(value)
143
+
144
+ raise api_module::InvalidRequestError.new(
145
+ "Could not determine which PATH to request: #{self} needs #{token}, got #{value.inspect}", token.to_s
146
+ )
147
+ end
148
+
149
+ def declare_path_template(template)
150
+ segments = parse_path_template(template)
151
+ tokens = segments.grep(Symbol)
152
+ validate_path_tokens!(template, tokens)
153
+
154
+ # Segments first: path_template_segments reads them once the
155
+ # template is set.
156
+ @path_template_segments = segments.freeze
157
+ @path_template = template
158
+ define_path_readers(tokens)
159
+ nil
160
+ end
161
+
162
+ def parse_path_template(template)
163
+ template.split("/").reject(&:blank?).map do |segment|
164
+ if Resteze::Util.dot_segment?(segment)
165
+ raise ArgumentError, "path_template #{template.inspect} has a #{segment.inspect} segment"
166
+ end
167
+ next segment unless segment.include?(":")
168
+
169
+ token = segment[TOKEN, 1] or
170
+ raise ArgumentError, "Invalid path_template segment #{segment.inspect}: a :token must be a whole " \
171
+ "segment named like a method (#{template.inspect})"
172
+ token.to_sym
173
+ end
174
+ end
175
+
176
+ def validate_path_tokens!(template, tokens)
177
+ raise ArgumentError, "path_template #{template.inspect} has no :tokens; set resource_slug instead" if tokens.empty?
178
+ raise ArgumentError, "path_template #{template.inspect} repeats a token" if tokens.uniq.size != tokens.size
179
+
180
+ reserved = tokens & RESERVED
181
+ raise ArgumentError, "path_template token :#{reserved.first} is reserved" if reserved.any?
182
+
183
+ clash = tokens.find { |token| shadows_method?(token) }
184
+ return unless clash
185
+
186
+ raise ArgumentError, "path_template token :#{clash} would shadow #{self}##{clash}; choose another name"
187
+ end
188
+
189
+ # True when a reader for the token would hide a method that is neither
190
+ # a declared property nor a reader an ancestor's template generated.
191
+ def shadows_method?(name)
192
+ return false if property?(name)
193
+ return false unless method_defined?(name) || private_method_defined?(name)
194
+
195
+ !instance_method(name).owner.is_a?(Readers)
196
+ end
197
+
198
+ def define_path_readers(tokens)
199
+ readers = Readers.new
200
+ tokens.reject { |token| property?(token) }.each do |token|
201
+ readers.define_method(token) { routing_path_params[token] }
202
+ end
203
+ readers.define_method(:parent) { path_parent } unless shadows_method?(:parent)
204
+ include readers
205
+ end
206
+ end
207
+ end
208
+ end
data/lib/resteze/save.rb CHANGED
@@ -21,9 +21,9 @@ module Resteze
21
21
  def save_resource_path
22
22
  action = save_action
23
23
  if action.rest_default?
24
- persisted? ? resource_path : self.class.resource_path
24
+ persisted? ? resource_path : self.class.resource_path(**routing_path_params)
25
25
  else
26
- persisted? ? action.path_for(id) : action.path_for
26
+ action.path_for((id if persisted?), routing_path_params)
27
27
  end
28
28
  end
29
29
 
@@ -43,7 +43,8 @@ module Resteze
43
43
  end
44
44
 
45
45
  def assert_action_path(action, path)
46
- actual = action.member? ? action.path_for("ID") : action.path_for
46
+ tokens = subject.path_tokens.index_with { |token| token.to_s.upcase }
47
+ actual = action.path_for(("ID" if action.member?), tokens)
47
48
 
48
49
  assert_equal path, actual, "Expected #{subject} action #{action.name} to route to #{path}"
49
50
  end
@@ -2,7 +2,8 @@ module Resteze
2
2
  module Testing
3
3
  module RSpec
4
4
  module Object
5
- extend RSpec::Matchers
5
+ # ::RSpec, since a bare RSpec here is Resteze::Testing::RSpec.
6
+ extend ::RSpec::Matchers
6
7
 
7
8
  ACTION_READERS = { method: :http_method, on: :on, id: :id, id_param: :id_param,
8
9
  returns: :returns, as: :generated_name }.freeze
@@ -52,7 +53,8 @@ module Resteze
52
53
  end
53
54
 
54
55
  def assert_action_path(action, path)
55
- actual = action.member? ? action.path_for("ID") : action.path_for
56
+ tokens = subject.path_tokens.index_with { |token| token.to_s.upcase }
57
+ actual = action.path_for(("ID" if action.member?), tokens)
56
58
 
57
59
  expect(actual).to eq(path), "Expected #{subject} action #{action.name} to route to #{path}"
58
60
  end
data/lib/resteze/util.rb CHANGED
@@ -2,6 +2,8 @@ module Resteze
2
2
  module Util
3
3
  extend ActiveSupport::Concern
4
4
 
5
+ DOT_SEGMENTS = %w[. ..].freeze
6
+
5
7
  module ClassMethods
6
8
  def convert_to_object(data, object_class)
7
9
  case data
@@ -14,6 +16,19 @@ module Resteze
14
16
  end
15
17
  end
16
18
 
19
+ # Encodes a value for use as one segment of a URL path. This is
20
+ # percent-encoding, not form encoding: a space becomes %20, where
21
+ # CGI.escape would write a "+" that a server reads literally in a path.
22
+ def encode_path_segment(value)
23
+ ERB::Util.url_encode(value.to_s)
24
+ end
25
+
26
+ # True for "." and "..", which a URL resolves as "this directory" and
27
+ # "up one": as a path segment either would leave the intended path.
28
+ def dot_segment?(value)
29
+ DOT_SEGMENTS.include?(value.to_s)
30
+ end
31
+
17
32
  def normalize_headers(headers)
18
33
  headers.transform_keys { |key| capitalize_parts(key) }
19
34
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Resteze
4
- VERSION = "1.0.0"
4
+ VERSION = "1.1.0"
5
5
  end
data/lib/resteze.rb CHANGED
@@ -1,6 +1,7 @@
1
1
  # Dependencies
2
2
  require "action_dispatch/http/mime_type"
3
3
  require "active_support/all"
4
+ require "erb"
4
5
  require "faraday"
5
6
  require "hashie"
6
7
  require "logger"
@@ -12,9 +13,11 @@ require "resteze/api_module"
12
13
  require "resteze/request"
13
14
  require "resteze/actions/validation"
14
15
  require "resteze/actions"
16
+ require "resteze/path_template"
15
17
  require "resteze/api_resource"
16
18
  require "resteze/list"
17
19
  require "resteze/save"
20
+ require "resteze/destroy"
18
21
 
19
22
  # API resource support classes
20
23
  require "resteze/object"
@@ -212,6 +215,11 @@ module Resteze
212
215
  include Resteze::Save
213
216
  end
214
217
 
218
+ const_set(:Destroy, Module.new).module_eval do
219
+ extend ActiveSupport::Concern
220
+ include Resteze::Destroy
221
+ end
222
+
215
223
  const_set(:Util, Module.new).module_eval do
216
224
  include Resteze::Util
217
225
  end
metadata CHANGED
@@ -1,13 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: resteze
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.0.0
4
+ version: 1.1.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - JD Hendrickson
8
8
  bindir: bin
9
9
  cert_chain: []
10
- date: 2026-11-13 00:00:00.000000000 Z
10
+ date: 2026-11-17 00:00:00.000000000 Z
11
11
  dependencies:
12
12
  - !ruby/object:Gem::Dependency
13
13
  name: actionpack
@@ -75,6 +75,7 @@ files:
75
75
  - ".rubocop"
76
76
  - ".rubocop.yml"
77
77
  - ".ruby-version"
78
+ - AGENTS.md
78
79
  - CHANGELOG.md
79
80
  - CLAUDE.md
80
81
  - Guardfile
@@ -86,8 +87,10 @@ files:
86
87
  - docs/ACTIONS.md
87
88
  - docs/ADVANCED_USAGE.md
88
89
  - docs/API.md
90
+ - docs/BUILDING_A_CLIENT.md
89
91
  - docs/CONFIGURATION.md
90
92
  - docs/ERROR_HANDLING.md
93
+ - docs/NESTED_RESOURCES.md
91
94
  - docs/TESTING.md
92
95
  - lib/resteze.rb
93
96
  - lib/resteze/action.rb
@@ -103,12 +106,14 @@ files:
103
106
  - lib/resteze/authenticator/mtls.rb
104
107
  - lib/resteze/authenticator/strategy.rb
105
108
  - lib/resteze/client.rb
109
+ - lib/resteze/destroy.rb
106
110
  - lib/resteze/errors.rb
107
111
  - lib/resteze/instrumentation.rb
108
112
  - lib/resteze/list.rb
109
113
  - lib/resteze/list_object.rb
110
114
  - lib/resteze/middleware/raise_error.rb
111
115
  - lib/resteze/object.rb
116
+ - lib/resteze/path_template.rb
112
117
  - lib/resteze/rate_limit.rb
113
118
  - lib/resteze/rate_limiter.rb
114
119
  - lib/resteze/rate_limiter/fixed_window.rb