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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 7bf2fb41e39a2e7383f9977bca343aaeba1ae30be302ba13acb3c3a63dc85bea
4
- data.tar.gz: c88e04e781ea1c857ab040d0873333e13ea810dd91f8add7690e5c0539af7090
3
+ metadata.gz: af20a855731c6d0761cfe05a1b41e6ed239651b3a034d2cf2b5bc995fd66d35f
4
+ data.tar.gz: 2cbcd832a490d2fe01b4375aef6bfa40e1cd22c35d6be37496920cce2330a112
5
5
  SHA512:
6
- metadata.gz: 3f44dec43d6bd1838ac8962e30f28f175529cac474062659ab90847262f714faaafbce4e6cf5c7cffdc8e1ab085cf12c4aff591bf13ad3d0a6b43639299bac0a
7
- data.tar.gz: a0c4429efa6a62b1060e150625c7c1e302ba90d19b471005a7ce42c222ad2e8911be89f208d0e6e581140095351cb3a613669a5c4f2165836e7edbe1aa2ff984
6
+ metadata.gz: 5baba23c10f2903219fb094adcf28327f8d2f5a1651bdfaff60e840381ddab53d6fc4d8c57692b86f70fb34c57db2bf04057ce5d62492538aa7645db46bca668
7
+ data.tar.gz: f919f6e64ff6f713a743e537b784ee77aa1c39c9223bd5b7533eac394cebc6fae0d34addd62500dc357fead73965f432a0835656fc2ef361ce1696597fcf2814
data/AGENTS.md ADDED
@@ -0,0 +1,122 @@
1
+ # AGENTS.md
2
+
3
+ Guidance for AI coding agents. There are two audiences, so find yours first:
4
+
5
+ - **You are building or changing a client gem that uses Resteze.** Read
6
+ [Using Resteze in a client](#using-resteze-in-a-client), then
7
+ [docs/BUILDING_A_CLIENT.md](docs/BUILDING_A_CLIENT.md).
8
+ - **You are working on Resteze itself**, in this repository. Read from
9
+ [About](#about) onward.
10
+
11
+ ## Using Resteze in a client
12
+
13
+ Resteze is a framework for REST API client gems. A client is a module that
14
+ does `include Resteze`, plus one small class per resource.
15
+
16
+ 1. Read [docs/BUILDING_A_CLIENT.md](docs/BUILDING_A_CLIENT.md) first. It maps
17
+ what an API looks like to the feature to use, shows a complete client, and
18
+ lists what not to do. The other files in `docs/` are reference.
19
+ 2. The docs ship inside the gem. In a client project, `bundle info resteze
20
+ --path` prints where it is installed; `docs/` and this file are there.
21
+ 3. Prefer a declaration to an override. Nested paths are `path_template`,
22
+ extra endpoints are `action`, authentication is `authenticate_with`,
23
+ pacing is `rate_limit_with`. If you are about to override `resource_path`,
24
+ `list` or `retrieve_params`, or to build a URL by hand, stop and check
25
+ the guide's table.
26
+ 4. Inside the module, use the per-module classes by their short names:
27
+ `class Widget < ApiResource`, `include List`, `rescue WidgetApi::Error`.
28
+ Never rescue `Faraday::` classes or inherit from `Resteze::Object`.
29
+ 5. Test declarations with `has_property` and `has_action` from
30
+ `resteze/testing/minitest` or `resteze/testing/rspec`, and requests with
31
+ WebMock.
32
+
33
+ The rest of this file is for work on Resteze itself.
34
+
35
+ ## About
36
+
37
+ Resteze is a Ruby gem that provides a framework for building REST API client libraries. Consumers `include Resteze` in their own module and get a fully namespaced set of classes (Client, ApiResource, ListObject, Error hierarchy, etc.) that they extend to define resources.
38
+
39
+ ## Commands
40
+
41
+ ```bash
42
+ bundle exec rake # Run tests + RuboCop (default task)
43
+ bundle exec rake test # Run tests only
44
+ bundle exec rake rubocop # Lint only
45
+ bundle exec ruby -Ilib:test test/resteze/client_test.rb # Run a single test file
46
+ bundle exec guard # Watch mode: re-runs tests on file changes
47
+ COVERAGE=1 bundle exec rake test # Run tests with coverage report
48
+ ```
49
+
50
+ ## Architecture
51
+
52
+ ### The `include Resteze` pattern
53
+
54
+ When a module does `include Resteze`, the `included` block in `lib/resteze.rb` fires and sets up a full set of namespaced constants inside the consuming module:
55
+
56
+ - `MyApi::Object` — base Hashie::Trash subclass for all resource objects
57
+ - `MyApi::Client` — Faraday-based HTTP client (thread-safe via `Thread.current`)
58
+ - `MyApi::ApiResource` — extends Object with `retrieve`, `resource_path`, `refresh`
59
+ - `MyApi::ListObject` — Hashie::Array subclass for paginated list responses
60
+ - `MyApi::Result` — Hashie::Mash subclass returned by custom actions that declare no `returns:`
61
+ - `MyApi::Middleware::RaiseError` — Faraday middleware for HTTP error handling
62
+ - `MyApi::List`, `MyApi::Save`, `MyApi::Destroy` — mixins consumers include on specific resources
63
+ - `MyApi::Error` and all subclasses — namespaced error hierarchy
64
+ - `MyApi::Authenticator` — per-module `Resteze::Authenticator` subclass; `MyApi.authenticator` is the thread-shared instance. `authenticate_with <name or Strategy class>, **options` on the module (or `strategy` inside the class; combinable) adds a `Resteze::Authenticator::Strategy` subclass; built-in schemes call `Strategy.register(:name, self)` (`lib/resteze/authenticator/`), and a gem can register its own. A strategy's `DEFAULTS` name the module settings it expects, which `authenticate_with` declares. `Resteze::Authenticating` is prepended on `Client` to call `apply(request)` before each request and retry once when `refresh?` says so; `connection_options` feed `Client.default_connection`
65
+ - `MyApi::RateLimiter` — per-module `Resteze::RateLimiter` subclass; `MyApi.rate_limiter` is the thread-shared instance the client consults (`before_request`, `track`, `retry?`, `retry_after`, `rate_limit`). `strategy :fixed_window | :sliding_window | :token_bucket | :leaky_bucket, **options` picks a built-in algorithm (`lib/resteze/rate_limiter/`); `Resteze::RateLimiting` is prepended outermost on `Client` to drive it and retry
66
+
67
+ This means each consuming gem gets its own isolated class hierarchy; errors from one API won't be caught by rescue clauses for another.
68
+
69
+ ### `ApiModule` — the ancestry resolver
70
+
71
+ `Resteze::ApiModule` is mixed into every class in the hierarchy. Its `api_module` class method walks the constant name ancestry (`Widget` → `MyApi::Widget` → `MyApi`) to find the module that `include`d Resteze. This is what allows `MyApi::Widget.request(...)` to automatically use `MyApi::Client` rather than needing any explicit wiring.
72
+
73
+ ### Request flow
74
+
75
+ ```
76
+ MyApi::Widget.retrieve(id)
77
+ → ApiResource#refresh
78
+ → Request.request(:get, path)
79
+ → MyApi::Client.active_client.execute_request(method, path)
80
+ → Faraday connection (thread-local default_client)
81
+ → Middleware::RaiseError
82
+ → Response.from_faraday_response
83
+ → Object#initialize_from(resp.data)
84
+ ```
85
+
86
+ GET/HEAD/DELETE params become query strings; all other methods send a JSON body.
87
+
88
+ ### Object / property system
89
+
90
+ `Resteze::Object` extends `Hashie::Trash`, which provides typed `property` declarations with optional transforms, defaults, and translations (key remapping). Unknown keys that don't match a declared property are stored in `@property_bag` rather than raising, allowing forward compatibility with API changes.
91
+
92
+ `object_key` (default: `nil`) lets a resource unwrap a top-level envelope key from API responses. `list_key` (default: `:data`) tells `ListObject` which key holds the array of items.
93
+
94
+ ### Mixins: List, Save and Destroy
95
+
96
+ - **`Resteze::List`** adds a class-level `.list(params:)` that issues a GET to `resource_path` and constructs a `ListObject`.
97
+ - **`Resteze::Save`** adds `#save` which issues POST (new) or PUT (persisted) based on `persisted?` (presence of `id`).
98
+ - **`Resteze::Destroy`** adds `#destroy` and `.destroy(id)`, which issue DELETE to `resource_path` and return a `Result` via the overridable `process_destroy_response`.
99
+
100
+ All three are opt-in; include them on a resource class when needed.
101
+
102
+ ### Actions: the routing DSL
103
+
104
+ `Resteze::Actions` (mixed into `ApiResource`) provides a Rails-style `action` DSL. `action :track, method: :post` on a resource generates `Klass.track(**params)`; `on: :member` generates an instance method plus `Klass.name(id, **params)`. Five names are reserved (`retrieve`, `list`, `create`, `update`, `destroy`): they are pre-registered with REST defaults, never generate methods, and can be re-routed by redeclaring them (`action :retrieve, path: "details", id: :param`).
105
+
106
+ Resolution is lazy. `Klass.actions` rebuilds a frozen hash of `Resteze::Action` value objects on every call by merging, lowest priority first: `Action::BUILT_IN` → the module's `action_defaults` → the module's `action` declarations → ancestor classes' `declared_actions` → the class's own. `refresh`, `list`, `save` and `destroy` consult the registry for their route (`retrieve_resource_path`, `list_resource_path`, `save_resource_path`, `save_params`, `destroy_resource_path`, `destroy_params`) but keep their own bodies. Custom actions return `MyApi::Result` (a `Hashie::Mash`) unless `returns:` names `:self`, `:list` or an `Object` subclass. Declaration-time validation lives in `Resteze::Actions::Validation`. See `docs/ACTIONS.md`.
107
+
108
+ ### Nested resources: `path_template`
109
+
110
+ `Resteze::PathTemplate` (mixed into `ApiResource`) lets a resource declare `path_template "catalogs/:catalog_name/items"`. `Klass.nested?` is true for such a class and `Klass.path_tokens` lists the token names (the class has no `path_params`; that is the instance's hash of values). `resource_path(id, **path_params)` fills it and `Action#path_for(id, path_params)` passes the values through, so every built-in and custom action nests, `destroy` included (`Item.destroy(id, catalog_name: "shoes")`). Class methods (`list`, `retrieve`, `new`, class forms of actions) take the tokens and an optional `parent:` as keywords via `partition_path_keywords` / `path_context!`; instances hold them outside the properties (`path_params`, `path_parent`, generated readers) and objects built by a call get them through `apply_path_context`. The instance form of a member action treats every keyword as a request param. There is no association layer. See `docs/NESTED_RESOURCES.md`.
111
+
112
+ ### Documentation is tested
113
+
114
+ `test/docs_test.rb` checks `README.md`, `AGENTS.md` and `docs/*.md` against the gem: every `ruby` example must parse, every file under `resteze/` that an example requires must load, every `Resteze::` constant must exist, and every `include`d mixin must be one Resteze defines. When you add or rename a public name, update the docs in the same change; when an example is not Ruby, fence it as something else (`yaml`, `text`).
115
+
116
+ ### Testing helpers
117
+
118
+ `lib/resteze/testing/` provides helpers for consumers testing their own gem:
119
+ - `Resteze::Testing::Minitest` — `has_property` assertion helper and `assert_config_property`
120
+ - `Resteze::Testing::RSpec` — equivalent helpers for RSpec
121
+
122
+ The gem's own tests use **Minitest** with **WebMock** (net connections disabled globally). The test helper defines `AcmeApi` as a reference implementation of a consuming module.
data/CHANGELOG.md CHANGED
@@ -2,6 +2,26 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [1.1.0]
6
+
7
+ ### Added
8
+
9
+ - `path_template` on `ApiResource` for nested resources: `path_template "catalogs/:catalog_name/items"` routes `retrieve`, `list`, `save`, `destroy`, `refresh` and every action under the filled template. Class methods take the tokens as keywords (`Item.list(catalog_name: "shoes")`), instances remember them (`item.catalog_name`, `item.path_params`), `Item.nested?` says whether a resource has a template, and a missing value, or a `.` / `..` one, raises `InvalidRequestError` naming it. See `docs/NESTED_RESOURCES.md`.
10
+ - `parent:` keyword on a templated resource's `list`, `retrieve`, `new` and action methods: a plain reference handed to every object the call builds, readable as `item.parent`.
11
+ - `has_action ... path:` fills a nested resource's tokens with their upcased names (`/catalogs/CATALOG_NAME/items/ID`).
12
+ - `destroy` built-in action (DELETE, member, id in the path) and the opt-in `Destroy` mixin, which adds `#destroy` and `.destroy(id)` returning a `Result` via `process_destroy_response`.
13
+
14
+ ### Changed
15
+
16
+ - `resource_path`, `Action#path_for`, `list`, `list_resource_path`, `retrieve`, `invoke_action` and `ApiResource#initialize` accept path values. Resources without a `path_template` behave as before, including overrides of these methods with their 1.0.0 signatures.
17
+ - Ids, action path segments and path values are percent-encoded for a URL path (`ERB::Util.url_encode`) rather than form-encoded (`CGI.escape`). The visible difference is a space, which is now sent as `%20`: it was sent as `+`, which a server reads as a literal plus sign in a path.
18
+ - An id of `.` or `..` raises `InvalidRequestError` before any request, as a path value does; so does a blank id passed to the class-level `resource_path`, which used to build a path with a trailing slash. A `.` or `..` segment in an action's `path:` or in a `path_template` raises `ArgumentError` at declaration.
19
+ - `retrieve` with no arguments now raises `InvalidRequestError` (invalid ID) rather than `ArgumentError`.
20
+
21
+ ### Fixed
22
+
23
+ - `require "resteze/testing/rspec"` raised `NameError` (`Resteze::Testing::RSpec::Matchers`), so the RSpec helpers could not be loaded. They load now and have their own tests.
24
+
5
25
  ## [1.0.0]
6
26
 
7
27
  The release developed as 0.5.0, renumbered: it is the first stable release, and the error hierarchy change under **Changed** breaks code written against the Faraday-derived classes.
@@ -22,7 +42,7 @@ The release developed as 0.5.0, renumbered: it is the first stable release, and
22
42
  - `Error.from_faraday` builds a namespaced error from a Faraday error, keeping its status, headers, body, parsed `json_body` and response; `Error#header` looks a header up case-insensitively.
23
43
  - `Response.body_error` hook for APIs that report failures inside a 2xx body. Override it on `MyApi::Response` to return an error to raise; `Error.from_response` builds one from the parsed response.
24
44
  - `MyApi::RateLimiter`, a per-module subclass of `Resteze::RateLimiter` through which a client describes and responds to its API's rate limiting. The client calls one thread-shared instance (`MyApi.rate_limiter`) at fixed points: `before_request`, `track` after every response or error, `retry?` and `retry_after` after a 429, and `rate_limit` when `Response#rate_limit` or `Error#rate_limit` is read. Every method is a no-op by default; Resteze assumes nothing about the mechanics. State lives in a mutex-guarded hash (`state`, `update_state`, `synchronize`) so subclasses need not manage threads.
25
- - Four built-in strategies, chosen with `strategy` in the module's `RateLimiter`: `:fixed_window` (with optional `headers: true` to follow the API's `X-RateLimit-*` headers, as Braze and JD Power report), `:sliding_window`, `:token_bucket` and `:leaky_bucket`. A strategy makes `before_request` wait until the request fits and `rate_limit` return a `Resteze::RateLimit` of its current view. `on_wait: :raise` raises `RateLimitError` with the wait in `retry_after` instead of sleeping, for callers such as background jobs that reschedule themselves, and applies to retry waits too. `max_wait:` (default one hour) clamps every wait, so a bad `Retry-After` or reset header cannot park a thread indefinitely or crash on a non-finite sleep. Custom algorithms subclass `Resteze::RateLimiter::Strategy`.
45
+ - Four built-in strategies, chosen with `strategy` in the module's `RateLimiter`: `:fixed_window` (with optional `headers: true` to follow the API's `X-RateLimit-*` headers, as many APIs report), `:sliding_window`, `:token_bucket` and `:leaky_bucket`. A strategy makes `before_request` wait until the request fits and `rate_limit` return a `Resteze::RateLimit` of its current view. `on_wait: :raise` raises `RateLimitError` with the wait in `retry_after` instead of sleeping, for callers such as background jobs that reschedule themselves, and applies to retry waits too. `max_wait:` (default one hour) clamps every wait, so a bad `Retry-After` or reset header cannot park a thread indefinitely or crash on a non-finite sleep. Custom algorithms subclass `Resteze::RateLimiter::Strategy`.
26
46
  - `RateLimitError#retry_after` reads the HTTP `Retry-After` header (delay-seconds or HTTP-date); `Resteze::RateLimit.from_headers` is a helper for the three-header shape.
27
47
  - A `rate_limit.wait.<key>` notification fires whenever the `RateLimiter` makes a request wait, before sending or before a retry, with the wait's `seconds`, `reason`, `attempt` and `on_wait` in the payload and the time actually waited as its duration; under `on_wait: :raise` it carries the exception instead. The `request.<key>` payload gains `rate_limit`, the limiter's view of the quota, when it reports one.
28
48
 
data/CLAUDE.md CHANGED
@@ -1,83 +1,5 @@
1
1
  # CLAUDE.md
2
2
 
3
- This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
3
+ The guidance for this repository lives in `AGENTS.md`, so that every coding agent reads the same file.
4
4
 
5
- ## About
6
-
7
- Resteze is a Ruby gem that provides a framework for building REST API client libraries. Consumers `include Resteze` in their own module and get a fully namespaced set of classes (Client, ApiResource, ListObject, Error hierarchy, etc.) that they extend to define resources.
8
-
9
- ## Commands
10
-
11
- ```bash
12
- bundle exec rake # Run tests + RuboCop (default task)
13
- bundle exec rake test # Run tests only
14
- bundle exec rake rubocop # Lint only
15
- bundle exec ruby -Ilib:test test/resteze/client_test.rb # Run a single test file
16
- bundle exec guard # Watch mode: re-runs tests on file changes
17
- COVERAGE=1 bundle exec rake test # Run tests with coverage report
18
- ```
19
-
20
- ## Architecture
21
-
22
- ### The `include Resteze` pattern
23
-
24
- When a module does `include Resteze`, the `included` block in `lib/resteze.rb` fires and sets up a full set of namespaced constants inside the consuming module:
25
-
26
- - `MyApi::Object` — base Hashie::Trash subclass for all resource objects
27
- - `MyApi::Client` — Faraday-based HTTP client (thread-safe via `Thread.current`)
28
- - `MyApi::ApiResource` — extends Object with `retrieve`, `resource_path`, `refresh`
29
- - `MyApi::ListObject` — Hashie::Array subclass for paginated list responses
30
- - `MyApi::Result` — Hashie::Mash subclass returned by custom actions that declare no `returns:`
31
- - `MyApi::Middleware::RaiseError` — Faraday middleware for HTTP error handling
32
- - `MyApi::List`, `MyApi::Save` — mixins consumers include on specific resources
33
- - `MyApi::Error` and all subclasses — namespaced error hierarchy
34
- - `MyApi::Authenticator` — per-module `Resteze::Authenticator` subclass; `MyApi.authenticator` is the thread-shared instance. `authenticate_with <name or Strategy class>, **options` on the module (or `strategy` inside the class; combinable) adds a `Resteze::Authenticator::Strategy` subclass; built-in schemes call `Strategy.register(:name, self)` (`lib/resteze/authenticator/`), and a gem can register its own. A strategy's `DEFAULTS` name the module settings it expects, which `authenticate_with` declares. `Resteze::Authenticating` is prepended on `Client` to call `apply(request)` before each request and retry once when `refresh?` says so; `connection_options` feed `Client.default_connection`
35
- - `MyApi::RateLimiter` — per-module `Resteze::RateLimiter` subclass; `MyApi.rate_limiter` is the thread-shared instance the client consults (`before_request`, `track`, `retry?`, `retry_after`, `rate_limit`). `strategy :fixed_window | :sliding_window | :token_bucket | :leaky_bucket, **options` picks a built-in algorithm (`lib/resteze/rate_limiter/`); `Resteze::RateLimiting` is prepended outermost on `Client` to drive it and retry
36
-
37
- This means each consuming gem gets its own isolated class hierarchy; errors from one API won't be caught by rescue clauses for another.
38
-
39
- ### `ApiModule` — the ancestry resolver
40
-
41
- `Resteze::ApiModule` is mixed into every class in the hierarchy. Its `api_module` class method walks the constant name ancestry (`Widget` → `MyApi::Widget` → `MyApi`) to find the module that `include`d Resteze. This is what allows `MyApi::Widget.request(...)` to automatically use `MyApi::Client` rather than needing any explicit wiring.
42
-
43
- ### Request flow
44
-
45
- ```
46
- MyApi::Widget.retrieve(id)
47
- → ApiResource#refresh
48
- → Request.request(:get, path)
49
- → MyApi::Client.active_client.execute_request(method, path)
50
- → Faraday connection (thread-local default_client)
51
- → Middleware::RaiseError
52
- → Response.from_faraday_response
53
- → Object#initialize_from(resp.data)
54
- ```
55
-
56
- GET/HEAD/DELETE params become query strings; all other methods send a JSON body.
57
-
58
- ### Object / property system
59
-
60
- `Resteze::Object` extends `Hashie::Trash`, which provides typed `property` declarations with optional transforms, defaults, and translations (key remapping). Unknown keys that don't match a declared property are stored in `@property_bag` rather than raising, allowing forward compatibility with API changes.
61
-
62
- `object_key` (default: `nil`) lets a resource unwrap a top-level envelope key from API responses. `list_key` (default: `:data`) tells `ListObject` which key holds the array of items.
63
-
64
- ### Mixins: List and Save
65
-
66
- - **`Resteze::List`** adds a class-level `.list(params:)` that issues a GET to `resource_path` and constructs a `ListObject`.
67
- - **`Resteze::Save`** adds `#save` which issues POST (new) or PUT (persisted) based on `persisted?` (presence of `id`).
68
-
69
- Both are opt-in; include them on a resource class when needed.
70
-
71
- ### Actions: the routing DSL
72
-
73
- `Resteze::Actions` (mixed into `ApiResource`) provides a Rails-style `action` DSL. `action :track, method: :post` on a resource generates `Klass.track(**params)`; `on: :member` generates an instance method plus `Klass.name(id, **params)`. Four names are reserved (`retrieve`, `list`, `create`, `update`): they are pre-registered with REST defaults, never generate methods, and can be re-routed by redeclaring them (`action :retrieve, path: "details", id: :param`).
74
-
75
- Resolution is lazy. `Klass.actions` rebuilds a frozen hash of `Resteze::Action` value objects on every call by merging, lowest priority first: `Action::BUILT_IN` → the module's `action_defaults` → the module's `action` declarations → ancestor classes' `declared_actions` → the class's own. `refresh`, `list` and `save` consult the registry for their route (`retrieve_resource_path`, `list_resource_path`, `save_resource_path`, `save_params`) but keep their own bodies. Custom actions return `MyApi::Result` (a `Hashie::Mash`) unless `returns:` names `:self`, `:list` or an `Object` subclass. Declaration-time validation lives in `Resteze::Actions::Validation`. See `docs/ACTIONS.md`.
76
-
77
- ### Testing helpers
78
-
79
- `lib/resteze/testing/` provides helpers for consumers testing their own gem:
80
- - `Resteze::Testing::Minitest` — `has_property` assertion helper and `assert_config_property`
81
- - `Resteze::Testing::RSpec` — equivalent helpers for RSpec
82
-
83
- The gem's own tests use **Minitest** with **WebMock** (net connections disabled globally). The test helper defines `AcmeApi` as a reference implementation of a consuming module.
5
+ @AGENTS.md
data/README.md CHANGED
@@ -97,6 +97,8 @@ module MyCoolApi
97
97
  end
98
98
  ```
99
99
 
100
+ Deleting is opt-in like `List` and `Save`: `include Destroy` adds `widget.destroy` and `Widget.destroy(id)`, routed by the built-in `destroy` action (`DELETE /widgets/:id` unless re-routed).
101
+
100
102
  ### Instrumentation
101
103
 
102
104
  Resteze fires an `ActiveSupport::Notifications` event for every HTTP request, making it easy to track performance metrics in host applications.
@@ -143,8 +145,10 @@ end
143
145
 
144
146
  ## Documentation
145
147
 
148
+ - [Building a Client](docs/BUILDING_A_CLIENT.md) — start here: what the API looks like, what to use, a complete client, and what not to do
146
149
  - [API](docs/API.md) — core concepts, resource definition, requests and responses
147
150
  - [Actions](docs/ACTIONS.md) — the `action` routing DSL for custom and re-routed endpoints
151
+ - [Nested Resources](docs/NESTED_RESOURCES.md) — `path_template` for resources that live under a parent
148
152
  - [Advanced Usage](docs/ADVANCED_USAGE.md) — lists, saves, pagination, batching and caching patterns
149
153
  - [Configuration](docs/CONFIGURATION.md) — module configuration, connections and middleware
150
154
  - [Error Handling](docs/ERROR_HANDLING.md) — the namespaced error hierarchy and recovery
data/docs/ACTIONS.md CHANGED
@@ -10,8 +10,8 @@ pattern at all.
10
10
  The `action` DSL, modeled on the Rails routing DSL for custom resource actions,
11
11
  covers both. A resource declares the actions it supports; each action resolves to
12
12
  an HTTP method, a path and a return type. The built-in `retrieve`, `list`,
13
- `create` and `update` are ordinary actions with REST defaults, so re-routing one
14
- uses the same vocabulary as adding a new one.
13
+ `create`, `update` and `destroy` are ordinary actions with REST defaults, so
14
+ re-routing one uses the same vocabulary as adding a new one.
15
15
 
16
16
  **A resource that declares nothing behaves exactly as it did before.**
17
17
 
@@ -19,6 +19,7 @@ uses the same vocabulary as adding a new one.
19
19
  - [Declaring custom actions](#declaring-custom-actions)
20
20
  - [Collection and member actions](#collection-and-member-actions)
21
21
  - [Re-routing the built-in actions](#re-routing-the-built-in-actions)
22
+ - [Destroying records](#destroying-records)
22
23
  - [API-wide defaults](#api-wide-defaults)
23
24
  - [Lookup order](#lookup-order)
24
25
  - [Return values](#return-values)
@@ -70,7 +71,6 @@ an action whose method name already exists on the class:
70
71
  ```ruby
71
72
  action :send, method: :post # ArgumentError: Object#send exists; pass as:
72
73
  action :send, method: :post, as: :deliver # MyApi::Message.deliver(...)
73
- action :delete, method: :post, on: :member, as: :destroy
74
74
  ```
75
75
 
76
76
  ## Collection and member actions
@@ -106,7 +106,7 @@ member action on a record with a blank id raises `MyApi::InvalidRequestError`.
106
106
 
107
107
  ## Re-routing the built-in actions
108
108
 
109
- Four names are reserved and pre-registered with REST defaults:
109
+ Five names are reserved and pre-registered with REST defaults:
110
110
 
111
111
  | Name | Method | Scope | Path | Id |
112
112
  |---|---|---|---|---|
@@ -114,16 +114,19 @@ Four names are reserved and pre-registered with REST defaults:
114
114
  | `list` | GET | collection | none | n/a |
115
115
  | `create` | POST | collection | none | n/a |
116
116
  | `update` | PUT | member | none | `:path` |
117
+ | `destroy` | DELETE | member | none | `:path` |
117
118
 
118
119
  Redeclaring one replaces its route. Options you leave out fall through to the
119
120
  next level of the [lookup order](#lookup-order), so changing just the path is one
120
- line. The existing `retrieve`, `list` and `save` methods keep their behavior and
121
- only pick up the new route; no new method is generated for a reserved name.
121
+ line. The existing `retrieve`, `list`, `save` and `destroy` methods keep their
122
+ behavior and only pick up the new route; no new method is generated for a
123
+ reserved name.
122
124
 
123
125
  ```ruby
124
126
  class ContentBlock < ApiResource
125
127
  include List
126
128
  include Save
129
+ include Destroy
127
130
 
128
131
  property :id
129
132
 
@@ -132,9 +135,37 @@ class ContentBlock < ApiResource
132
135
  action :create, path: "create" # POST /content_blocks/create
133
136
  action :update, path: "update", method: :post, id: :param
134
137
  # => POST /content_blocks/update with content_block_id in the body
138
+ action :destroy, path: "delete", method: :post, id: :param
139
+ # => POST /content_blocks/delete with content_block_id in the body
135
140
  end
136
141
  ```
137
142
 
143
+ ## Destroying records
144
+
145
+ Like `list` and `save`, the `destroy` method is opt-in through a mixin, so a
146
+ resource that must never be deleted does not grow the method by accident. The
147
+ route is the built-in `destroy` action: `DELETE /widgets/:id` unless re-routed.
148
+
149
+ ```ruby
150
+ class Widget < ApiResource
151
+ include Destroy
152
+
153
+ property :id
154
+ end
155
+
156
+ widget.destroy # DELETE /widgets/42
157
+ MyApi::Widget.destroy("42") # same request
158
+ ```
159
+
160
+ `destroy` returns a `MyApi::Result` built from the response, empty for a
161
+ `204 No Content`, and raises `MyApi::InvalidRequestError` on a blank id before
162
+ any request is made. Override `process_destroy_response(response)` to return
163
+ something else, such as `true` or the receiver.
164
+
165
+ Declaring `action :destroy` without the mixin only sets the route; it never
166
+ generates a method. The name `delete` is not available for a custom action
167
+ because every resource already has `Hash#delete`.
168
+
138
169
  ## API-wide defaults
139
170
 
140
171
  When a whole API follows one convention, declare it once on the module. The same
@@ -192,7 +223,7 @@ classes load, or on the resource itself.
192
223
 
193
224
  An action's options are merged lowest priority first:
194
225
 
195
- 1. REST built-in defaults, for the four reserved names.
226
+ 1. REST built-in defaults, for the five reserved names.
196
227
  2. The module's `action_defaults`.
197
228
  3. The module's `action` declaration for that name.
198
229
  4. Each ancestor resource class's declaration, farthest first.
@@ -216,7 +247,7 @@ class User < ApiResource
216
247
  action :track, method: :post
217
248
  end
218
249
 
219
- result = MyApi::User.track(events: [...])
250
+ result = MyApi::User.track(events: [{ name: "signup" }])
220
251
  result.message # => "success"
221
252
  result.events_processed # => 2
222
253
  result.http_response.http_status # => 200
@@ -273,6 +304,8 @@ The built-ins expose their routed paths as overridable methods too:
273
304
  | `list_resource_path(params)` (class) | `list` |
274
305
  | `save_resource_path` (instance) | `save` |
275
306
  | `save_params` (instance) | `save`; `as_save_json` plus the id param when `update` uses `id: :param` |
307
+ | `destroy_resource_path` (instance) | `destroy` |
308
+ | `destroy_params` (instance) | `destroy`; the id param when `destroy` uses `id: :param` |
276
309
  | `id_param` (class) | the default id param for every member action on the class |
277
310
 
278
311
  The instance method `resource_path` is unchanged. It still means "this record's
@@ -315,6 +348,16 @@ describe MyApi::Campaign do
315
348
  end
316
349
  ```
317
350
 
351
+ For a resource with a `path_template`, each token is filled with its upcased
352
+ name: `"/catalogs/CATALOG_NAME/items/ID/archive"`.
353
+
354
+ ## Nested resources
355
+
356
+ A resource that declares a `path_template` routes all of its actions under the
357
+ filled template. The class forms of generated methods take the template's
358
+ tokens as keywords; the instance form uses the values the instance remembers.
359
+ See [NESTED_RESOURCES.md](NESTED_RESOURCES.md).
360
+
318
361
  ## The escape hatch
319
362
 
320
363
  Anything the DSL does not express is still one `request` call away, exactly as
@@ -3,6 +3,7 @@
3
3
  ## Table of Contents
4
4
  - [List Operations](#list-operations)
5
5
  - [Save Operations](#save-operations)
6
+ - [Destroy Operations](#destroy-operations)
6
7
  - [Error Handling](#error-handling)
7
8
  - [Pagination](#pagination)
8
9
  - [Batch Operations](#batch-operations)
@@ -226,6 +227,60 @@ customers = MyApi::Customer.create_batch([
226
227
  ])
227
228
  ```
228
229
 
230
+ ## Destroy Operations
231
+
232
+ ### Including the Destroy Module
233
+
234
+ ```ruby
235
+ module MyApi
236
+ class Customer < ApiResource
237
+ include Destroy
238
+
239
+ property :id
240
+ property :email
241
+ end
242
+ end
243
+ ```
244
+
245
+ ### Deleting a Record
246
+
247
+ ```ruby
248
+ customer = MyApi::Customer.retrieve('123')
249
+ customer.destroy # DELETE /customers/123
250
+
251
+ MyApi::Customer.destroy('123') # same request, without retrieving first
252
+ ```
253
+
254
+ `destroy` returns a `MyApi::Result` built from the response body, which is empty
255
+ for a `204 No Content`. A blank id raises `MyApi::InvalidRequestError` before any
256
+ request is sent.
257
+
258
+ ### Custom Destroy Behavior
259
+
260
+ ```ruby
261
+ module MyApi
262
+ class Customer < ApiResource
263
+ include Destroy
264
+
265
+ property :id
266
+
267
+ # Send a reason with the request
268
+ def destroy_params
269
+ super.merge(reason: 'customer request')
270
+ end
271
+
272
+ # Return the receiver instead of a Result
273
+ def process_destroy_response(_response)
274
+ self
275
+ end
276
+ end
277
+ end
278
+ ```
279
+
280
+ `destroy_headers` defaults to `retrieve_headers` when defined. The route comes
281
+ from the built-in `destroy` action and can be re-routed like the others; see
282
+ [docs/ACTIONS.md](ACTIONS.md).
283
+
229
284
  ## Error Handling
230
285
 
231
286
  ### Built-in Error Classes
data/docs/API.md CHANGED
@@ -120,30 +120,28 @@ end
120
120
 
121
121
  ### Nested Resources
122
122
 
123
+ A resource that lives under a parent declares its path with `path_template`.
124
+ Each `:token` is filled per call and remembered by the instance:
125
+
123
126
  ```ruby
124
127
  module MyApi
125
128
  class Comment < ApiResource
129
+ include MyApi::List
130
+
126
131
  property :id
127
- property :post_id
128
132
  property :content
129
133
  property :author
130
-
131
- def self.resource_path(id = nil, post_id: nil)
132
- if post_id
133
- "/posts/#{post_id}/comments#{id ? "/#{id}" : ""}"
134
- else
135
- super(id)
136
- end
137
- end
138
-
139
- # Retrieve comments for a specific post
140
- def self.list_by_post(post_id)
141
- request(:get, resource_path(nil, post_id: post_id))
142
- end
134
+
135
+ path_template "posts/:post_id/comments"
143
136
  end
144
137
  end
138
+
139
+ MyApi::Comment.list(post_id: 42) # GET /posts/42/comments
140
+ MyApi::Comment.retrieve(7, post_id: 42) # GET /posts/42/comments/7
145
141
  ```
146
142
 
143
+ See [NESTED_RESOURCES.md](NESTED_RESOURCES.md).
144
+
147
145
  ## Making Requests
148
146
 
149
147
  ### Retrieving Resources