spikard 0.5.0 → 0.6.1

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.
Files changed (135) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +1 -1
  3. data/README.md +674 -674
  4. data/ext/spikard_rb/Cargo.toml +17 -17
  5. data/ext/spikard_rb/extconf.rb +13 -10
  6. data/ext/spikard_rb/src/lib.rs +6 -6
  7. data/lib/spikard/app.rb +405 -405
  8. data/lib/spikard/background.rb +27 -27
  9. data/lib/spikard/config.rb +396 -396
  10. data/lib/spikard/converters.rb +13 -13
  11. data/lib/spikard/handler_wrapper.rb +113 -113
  12. data/lib/spikard/provide.rb +214 -214
  13. data/lib/spikard/response.rb +173 -173
  14. data/lib/spikard/schema.rb +243 -243
  15. data/lib/spikard/sse.rb +111 -111
  16. data/lib/spikard/streaming_response.rb +44 -44
  17. data/lib/spikard/testing.rb +256 -256
  18. data/lib/spikard/upload_file.rb +131 -131
  19. data/lib/spikard/version.rb +5 -5
  20. data/lib/spikard/websocket.rb +59 -59
  21. data/lib/spikard.rb +43 -43
  22. data/sig/spikard.rbs +366 -366
  23. data/vendor/crates/spikard-bindings-shared/Cargo.toml +63 -63
  24. data/vendor/crates/spikard-bindings-shared/examples/config_extraction.rs +132 -132
  25. data/vendor/crates/spikard-bindings-shared/src/config_extractor.rs +752 -752
  26. data/vendor/crates/spikard-bindings-shared/src/conversion_traits.rs +194 -194
  27. data/vendor/crates/spikard-bindings-shared/src/di_traits.rs +246 -246
  28. data/vendor/crates/spikard-bindings-shared/src/error_response.rs +401 -401
  29. data/vendor/crates/spikard-bindings-shared/src/handler_base.rs +238 -238
  30. data/vendor/crates/spikard-bindings-shared/src/lib.rs +24 -24
  31. data/vendor/crates/spikard-bindings-shared/src/lifecycle_base.rs +292 -292
  32. data/vendor/crates/spikard-bindings-shared/src/lifecycle_executor.rs +616 -616
  33. data/vendor/crates/spikard-bindings-shared/src/response_builder.rs +305 -305
  34. data/vendor/crates/spikard-bindings-shared/src/test_client_base.rs +248 -248
  35. data/vendor/crates/spikard-bindings-shared/src/validation_helpers.rs +351 -351
  36. data/vendor/crates/spikard-bindings-shared/tests/comprehensive_coverage.rs +454 -454
  37. data/vendor/crates/spikard-bindings-shared/tests/error_response_edge_cases.rs +383 -383
  38. data/vendor/crates/spikard-bindings-shared/tests/handler_base_integration.rs +280 -280
  39. data/vendor/crates/spikard-core/Cargo.toml +40 -40
  40. data/vendor/crates/spikard-core/src/bindings/mod.rs +3 -3
  41. data/vendor/crates/spikard-core/src/bindings/response.rs +133 -133
  42. data/vendor/crates/spikard-core/src/debug.rs +127 -127
  43. data/vendor/crates/spikard-core/src/di/container.rs +702 -702
  44. data/vendor/crates/spikard-core/src/di/dependency.rs +273 -273
  45. data/vendor/crates/spikard-core/src/di/error.rs +118 -118
  46. data/vendor/crates/spikard-core/src/di/factory.rs +534 -534
  47. data/vendor/crates/spikard-core/src/di/graph.rs +506 -506
  48. data/vendor/crates/spikard-core/src/di/mod.rs +192 -192
  49. data/vendor/crates/spikard-core/src/di/resolved.rs +405 -405
  50. data/vendor/crates/spikard-core/src/di/value.rs +281 -281
  51. data/vendor/crates/spikard-core/src/errors.rs +69 -69
  52. data/vendor/crates/spikard-core/src/http.rs +415 -415
  53. data/vendor/crates/spikard-core/src/lib.rs +29 -29
  54. data/vendor/crates/spikard-core/src/lifecycle.rs +1186 -1186
  55. data/vendor/crates/spikard-core/src/metadata.rs +389 -389
  56. data/vendor/crates/spikard-core/src/parameters.rs +2525 -2525
  57. data/vendor/crates/spikard-core/src/problem.rs +344 -344
  58. data/vendor/crates/spikard-core/src/request_data.rs +1154 -1154
  59. data/vendor/crates/spikard-core/src/router.rs +510 -510
  60. data/vendor/crates/spikard-core/src/schema_registry.rs +183 -183
  61. data/vendor/crates/spikard-core/src/type_hints.rs +304 -304
  62. data/vendor/crates/spikard-core/src/validation/error_mapper.rs +696 -688
  63. data/vendor/crates/spikard-core/src/validation/mod.rs +457 -457
  64. data/vendor/crates/spikard-http/Cargo.toml +62 -64
  65. data/vendor/crates/spikard-http/examples/sse-notifications.rs +148 -148
  66. data/vendor/crates/spikard-http/examples/websocket-chat.rs +92 -92
  67. data/vendor/crates/spikard-http/src/auth.rs +296 -296
  68. data/vendor/crates/spikard-http/src/background.rs +1860 -1860
  69. data/vendor/crates/spikard-http/src/bindings/mod.rs +3 -3
  70. data/vendor/crates/spikard-http/src/bindings/response.rs +1 -1
  71. data/vendor/crates/spikard-http/src/body_metadata.rs +8 -8
  72. data/vendor/crates/spikard-http/src/cors.rs +1005 -1005
  73. data/vendor/crates/spikard-http/src/debug.rs +128 -128
  74. data/vendor/crates/spikard-http/src/di_handler.rs +1668 -1668
  75. data/vendor/crates/spikard-http/src/handler_response.rs +901 -901
  76. data/vendor/crates/spikard-http/src/handler_trait.rs +838 -830
  77. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +290 -290
  78. data/vendor/crates/spikard-http/src/lib.rs +534 -534
  79. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +230 -230
  80. data/vendor/crates/spikard-http/src/lifecycle.rs +1193 -1193
  81. data/vendor/crates/spikard-http/src/middleware/mod.rs +560 -540
  82. data/vendor/crates/spikard-http/src/middleware/multipart.rs +912 -912
  83. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +513 -513
  84. data/vendor/crates/spikard-http/src/middleware/validation.rs +768 -735
  85. data/vendor/crates/spikard-http/src/openapi/mod.rs +309 -309
  86. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +535 -535
  87. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +1363 -1363
  88. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +665 -665
  89. data/vendor/crates/spikard-http/src/query_parser.rs +793 -793
  90. data/vendor/crates/spikard-http/src/response.rs +720 -720
  91. data/vendor/crates/spikard-http/src/server/handler.rs +1650 -1650
  92. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +234 -234
  93. data/vendor/crates/spikard-http/src/server/mod.rs +1593 -1502
  94. data/vendor/crates/spikard-http/src/server/request_extraction.rs +789 -770
  95. data/vendor/crates/spikard-http/src/server/routing_factory.rs +629 -599
  96. data/vendor/crates/spikard-http/src/sse.rs +1409 -1409
  97. data/vendor/crates/spikard-http/src/testing/form.rs +52 -52
  98. data/vendor/crates/spikard-http/src/testing/multipart.rs +64 -60
  99. data/vendor/crates/spikard-http/src/testing/test_client.rs +311 -283
  100. data/vendor/crates/spikard-http/src/testing.rs +406 -377
  101. data/vendor/crates/spikard-http/src/websocket.rs +1404 -1375
  102. data/vendor/crates/spikard-http/tests/background_behavior.rs +832 -832
  103. data/vendor/crates/spikard-http/tests/common/handlers.rs +309 -309
  104. data/vendor/crates/spikard-http/tests/common/mod.rs +26 -26
  105. data/vendor/crates/spikard-http/tests/di_integration.rs +192 -192
  106. data/vendor/crates/spikard-http/tests/doc_snippets.rs +5 -5
  107. data/vendor/crates/spikard-http/tests/lifecycle_execution.rs +1093 -1093
  108. data/vendor/crates/spikard-http/tests/multipart_behavior.rs +656 -656
  109. data/vendor/crates/spikard-http/tests/server_config_builder.rs +314 -314
  110. data/vendor/crates/spikard-http/tests/sse_behavior.rs +620 -620
  111. data/vendor/crates/spikard-http/tests/websocket_behavior.rs +663 -663
  112. data/vendor/crates/spikard-rb/Cargo.toml +48 -48
  113. data/vendor/crates/spikard-rb/build.rs +199 -199
  114. data/vendor/crates/spikard-rb/src/background.rs +63 -63
  115. data/vendor/crates/spikard-rb/src/config/mod.rs +5 -5
  116. data/vendor/crates/spikard-rb/src/config/server_config.rs +285 -285
  117. data/vendor/crates/spikard-rb/src/conversion.rs +554 -554
  118. data/vendor/crates/spikard-rb/src/di/builder.rs +100 -100
  119. data/vendor/crates/spikard-rb/src/di/mod.rs +375 -375
  120. data/vendor/crates/spikard-rb/src/handler.rs +618 -618
  121. data/vendor/crates/spikard-rb/src/integration/mod.rs +3 -3
  122. data/vendor/crates/spikard-rb/src/lib.rs +1806 -1810
  123. data/vendor/crates/spikard-rb/src/lifecycle.rs +275 -275
  124. data/vendor/crates/spikard-rb/src/metadata/mod.rs +5 -5
  125. data/vendor/crates/spikard-rb/src/metadata/route_extraction.rs +442 -447
  126. data/vendor/crates/spikard-rb/src/runtime/mod.rs +5 -5
  127. data/vendor/crates/spikard-rb/src/runtime/server_runner.rs +324 -324
  128. data/vendor/crates/spikard-rb/src/server.rs +305 -308
  129. data/vendor/crates/spikard-rb/src/sse.rs +231 -231
  130. data/vendor/crates/spikard-rb/src/testing/client.rs +538 -551
  131. data/vendor/crates/spikard-rb/src/testing/mod.rs +7 -7
  132. data/vendor/crates/spikard-rb/src/testing/sse.rs +143 -143
  133. data/vendor/crates/spikard-rb/src/testing/websocket.rs +608 -635
  134. data/vendor/crates/spikard-rb/src/websocket.rs +377 -374
  135. metadata +15 -1
@@ -1,554 +1,554 @@
1
- //! Ruby ↔ Rust type conversion utilities.
2
- //!
3
- //! This module provides functions for converting between Ruby and Rust types,
4
- //! including JSON conversion, string conversion, and request/response building.
5
-
6
- #![allow(dead_code)]
7
- #![deny(clippy::unwrap_used)]
8
-
9
- use bytes::Bytes;
10
- use magnus::prelude::*;
11
- use magnus::{Error, RArray, RHash, RString, Ruby, Symbol, TryConvert, Value};
12
- use serde_json::Value as JsonValue;
13
- use spikard_core::problem::ProblemDetails;
14
- use spikard_http::testing::MultipartFilePart;
15
- use std::collections::HashMap;
16
-
17
- use crate::testing::client::{RequestBody, RequestConfig, TestResponseData};
18
-
19
- /// Convert a Ruby value to JSON.
20
- ///
21
- /// Fast-path converts common Ruby types directly in Rust to avoid
22
- /// `JSON.generate` + `serde_json::from_str` overhead.
23
- ///
24
- /// Falls back to Ruby JSON for unsupported types to preserve behavior.
25
- pub fn ruby_value_to_json(ruby: &Ruby, json_module: Value, value: Value) -> Result<JsonValue, Error> {
26
- if value.is_nil() {
27
- return Ok(JsonValue::Null);
28
- }
29
-
30
- if let Some(converted) = ruby_value_to_json_fast(ruby, json_module, value, 0)? {
31
- return Ok(converted);
32
- }
33
-
34
- ruby_value_to_json_fallback(ruby, json_module, value)
35
- }
36
-
37
- fn ruby_value_to_json_fallback(ruby: &Ruby, json_module: Value, value: Value) -> Result<JsonValue, Error> {
38
- let json_string: String = json_module.funcall("generate", (value,))?;
39
- serde_json::from_str(&json_string).map_err(|err| {
40
- Error::new(
41
- ruby.exception_runtime_error(),
42
- format!("Failed to convert Ruby value to JSON: {err}"),
43
- )
44
- })
45
- }
46
-
47
- fn ruby_value_to_json_fast(
48
- ruby: &Ruby,
49
- json_module: Value,
50
- value: Value,
51
- depth: usize,
52
- ) -> Result<Option<JsonValue>, Error> {
53
- // Cycle detection is non-trivial without tracking Ruby object IDs; a shallow
54
- // recursion guard avoids worst-case behavior and defers to Ruby JSON.
55
- if depth > 64 {
56
- return Ok(None);
57
- }
58
-
59
- if value.is_nil() {
60
- return Ok(Some(JsonValue::Null));
61
- }
62
-
63
- if value.is_kind_of(ruby.class_true_class()) {
64
- return Ok(Some(JsonValue::Bool(true)));
65
- }
66
-
67
- if value.is_kind_of(ruby.class_false_class()) {
68
- return Ok(Some(JsonValue::Bool(false)));
69
- }
70
-
71
- if let Ok(text) = RString::try_convert(value) {
72
- let slice = unsafe { text.as_slice() };
73
- return Ok(Some(JsonValue::String(String::from_utf8_lossy(slice).to_string())));
74
- }
75
-
76
- if value.is_kind_of(ruby.class_float()) {
77
- let n = f64::try_convert(value)?;
78
- let number = serde_json::Number::from_f64(n).ok_or_else(|| {
79
- Error::new(
80
- ruby.exception_runtime_error(),
81
- "Failed to convert Ruby Float to JSON number",
82
- )
83
- })?;
84
- return Ok(Some(JsonValue::Number(number)));
85
- }
86
-
87
- if value.is_kind_of(ruby.class_integer()) {
88
- if let Ok(n) = i64::try_convert(value) {
89
- return Ok(Some(JsonValue::from(n)));
90
- }
91
- if let Ok(n) = u64::try_convert(value) {
92
- return Ok(Some(JsonValue::from(n)));
93
- }
94
- }
95
-
96
- if let Some(array) = RArray::from_value(value) {
97
- let mut out = Vec::with_capacity(array.len());
98
- for idx in 0..array.len() {
99
- let item: Value = array.entry(idx as isize)?;
100
- let json_item = match ruby_value_to_json_fast(ruby, json_module, item, depth + 1)? {
101
- Some(v) => v,
102
- None => ruby_value_to_json_fallback(ruby, json_module, item)?,
103
- };
104
- out.push(json_item);
105
- }
106
- return Ok(Some(JsonValue::Array(out)));
107
- }
108
-
109
- if let Some(hash) = RHash::from_value(value) {
110
- let mut map = serde_json::Map::with_capacity(hash.len());
111
- hash.foreach(|key: Value, val: Value| {
112
- let key_str = if let Ok(key_text) = RString::try_convert(key) {
113
- let slice = unsafe { key_text.as_slice() };
114
- String::from_utf8_lossy(slice).to_string()
115
- } else if let Ok(sym) = Symbol::try_convert(key) {
116
- sym.name()?.into_owned()
117
- } else {
118
- let key_as_str: String = key.funcall("to_s", ())?;
119
- key_as_str
120
- };
121
-
122
- let json_val = match ruby_value_to_json_fast(ruby, json_module, val, depth + 1)? {
123
- Some(v) => v,
124
- None => ruby_value_to_json_fallback(ruby, json_module, val)?,
125
- };
126
-
127
- map.insert(key_str, json_val);
128
- Ok(magnus::r_hash::ForEach::Continue)
129
- })?;
130
- return Ok(Some(JsonValue::Object(map)));
131
- }
132
-
133
- Ok(None)
134
- }
135
-
136
- /// Convert JSON to a Ruby value.
137
- ///
138
- /// Recursively converts JSON types to native Ruby types:
139
- /// - null → nil
140
- /// - bool → true/false
141
- /// - number → integer or float
142
- /// - string → string
143
- /// - array → array
144
- /// - object → hash
145
- pub fn json_to_ruby(ruby: &Ruby, value: &JsonValue) -> Result<Value, Error> {
146
- json_to_ruby_with_uploads(ruby, value, None::<&Value>)
147
- }
148
-
149
- /// Convert JSON to a Ruby value, optionally materialising UploadFile objects.
150
- ///
151
- /// If `upload_file_class` is provided and the JSON object contains
152
- /// file-metadata keys (`filename`, `content`), this will instantiate
153
- /// `UploadFile` instead of returning a plain Hash.
154
- pub fn json_to_ruby_with_uploads(
155
- ruby: &Ruby,
156
- value: &JsonValue,
157
- upload_file_class: Option<&Value>,
158
- ) -> Result<Value, Error> {
159
- match value {
160
- JsonValue::Null => Ok(ruby.qnil().as_value()),
161
- JsonValue::Bool(b) => Ok(if *b {
162
- ruby.qtrue().as_value()
163
- } else {
164
- ruby.qfalse().as_value()
165
- }),
166
- JsonValue::Number(num) => {
167
- if let Some(i) = num.as_i64() {
168
- Ok(ruby.integer_from_i64(i).as_value())
169
- } else if let Some(f) = num.as_f64() {
170
- Ok(ruby.float_from_f64(f).as_value())
171
- } else {
172
- Ok(ruby.qnil().as_value())
173
- }
174
- }
175
- JsonValue::String(str_val) => Ok(ruby.str_new(str_val).as_value()),
176
- JsonValue::Array(items) => {
177
- let array = ruby.ary_new_capa(items.len());
178
- for item in items {
179
- array.push(json_to_ruby_with_uploads(ruby, item, upload_file_class)?)?;
180
- }
181
- Ok(array.as_value())
182
- }
183
- JsonValue::Object(map) => {
184
- if let Some(upload_file) = upload_file_class
185
- && let Some(upload) = try_build_upload_file(ruby, upload_file, map)?
186
- {
187
- return Ok(upload);
188
- }
189
-
190
- let hash = ruby.hash_new_capa(map.len());
191
- for (key, item) in map {
192
- hash.aset(
193
- ruby.str_new(key),
194
- json_to_ruby_with_uploads(ruby, item, upload_file_class)?,
195
- )?;
196
- }
197
- Ok(hash.as_value())
198
- }
199
- }
200
- }
201
-
202
- /// Convert a HashMap to a Ruby Hash.
203
- pub fn map_to_ruby_hash(ruby: &Ruby, map: &HashMap<String, String>) -> Result<Value, Error> {
204
- let hash = ruby.hash_new_capa(map.len());
205
- for (key, value) in map {
206
- hash.aset(ruby.str_new(key), ruby.str_new(value))?;
207
- }
208
- Ok(hash.as_value())
209
- }
210
-
211
- /// Convert a HashMap of Vecs to a Ruby Hash with array values.
212
- pub fn multimap_to_ruby_hash(ruby: &Ruby, map: &HashMap<String, Vec<String>>) -> Result<Value, Error> {
213
- let hash = ruby.hash_new_capa(map.len());
214
- for (key, values) in map {
215
- let array = ruby.ary_new_capa(values.len());
216
- for value in values {
217
- array.push(ruby.str_new(value))?;
218
- }
219
- hash.aset(ruby.str_new(key), array)?;
220
- }
221
- Ok(hash.as_value())
222
- }
223
-
224
- fn try_build_upload_file(
225
- ruby: &Ruby,
226
- upload_file_class: &Value,
227
- map: &serde_json::Map<String, JsonValue>,
228
- ) -> Result<Option<Value>, Error> {
229
- let filename = match map.get("filename").and_then(|v| v.as_str()) {
230
- Some(name) => name,
231
- None => return Ok(None),
232
- };
233
- let content = match map.get("content") {
234
- Some(JsonValue::String(s)) => s.as_str(),
235
- _ => return Ok(None),
236
- };
237
-
238
- let content_type = map.get("content_type").and_then(|v| v.as_str());
239
- let size = map.get("size").and_then(|v| v.as_u64());
240
- let headers_value = map
241
- .get("headers")
242
- .and_then(|v| v.as_object())
243
- .map(|obj| {
244
- obj.iter()
245
- .filter_map(|(k, v)| v.as_str().map(|val| (k.clone(), val.to_string())))
246
- .collect::<HashMap<String, String>>()
247
- })
248
- .unwrap_or_default();
249
- let headers = map_to_ruby_hash(ruby, &headers_value)?;
250
- let content_encoding = map.get("content_encoding").and_then(|v| v.as_str());
251
-
252
- let kwargs = magnus::kwargs!(
253
- "content_type" => content_type,
254
- "size" => size,
255
- "headers" => headers,
256
- "content_encoding" => content_encoding
257
- );
258
-
259
- let upload = upload_file_class.funcall("new", (filename, content, kwargs))?;
260
- Ok(Some(upload))
261
- }
262
-
263
- /// Convert a Ruby value to Bytes.
264
- ///
265
- /// Accepts either String or Array of bytes.
266
- pub fn ruby_value_to_bytes(value: Value) -> Result<Bytes, std::io::Error> {
267
- if let Ok(str_value) = RString::try_convert(value) {
268
- let slice = unsafe { str_value.as_slice() };
269
- return Ok(Bytes::copy_from_slice(slice));
270
- }
271
-
272
- if let Ok(vec_bytes) = Vec::<u8>::try_convert(value) {
273
- return Ok(Bytes::from(vec_bytes));
274
- }
275
-
276
- Err(std::io::Error::other(
277
- "Streaming chunks must be Strings or Arrays of bytes",
278
- ))
279
- }
280
-
281
- /// Convert a response to a Ruby Hash.
282
- pub fn response_to_ruby(ruby: &Ruby, response: TestResponseData) -> Result<Value, Error> {
283
- let hash = ruby.hash_new();
284
-
285
- hash.aset(
286
- ruby.intern("status_code"),
287
- ruby.integer_from_i64(response.status as i64),
288
- )?;
289
-
290
- let headers_hash = ruby.hash_new();
291
- for (key, value) in response.headers {
292
- headers_hash.aset(ruby.str_new(&key), ruby.str_new(&value))?;
293
- }
294
- hash.aset(ruby.intern("headers"), headers_hash)?;
295
-
296
- if let Some(body) = response.body_text {
297
- let body_value = ruby.str_new(&body);
298
- hash.aset(ruby.intern("body"), body_value)?;
299
- hash.aset(ruby.intern("body_text"), body_value)?;
300
- } else {
301
- hash.aset(ruby.intern("body"), ruby.qnil())?;
302
- hash.aset(ruby.intern("body_text"), ruby.qnil())?;
303
- }
304
-
305
- Ok(hash.as_value())
306
- }
307
-
308
- /// Convert a ProblemDetails to a JSON string.
309
- pub fn problem_to_json(problem: &ProblemDetails) -> String {
310
- problem
311
- .to_json_pretty()
312
- .unwrap_or_else(|err| format!("Failed to serialise problem details: {err}"))
313
- }
314
-
315
- /// Fetch a handler from a Ruby Hash by name.
316
- ///
317
- /// Tries both symbol and string keys.
318
- pub fn fetch_handler(ruby: &Ruby, handlers: &RHash, name: &str) -> Result<Value, Error> {
319
- let symbol_key = ruby.intern(name);
320
- if let Some(value) = handlers.get(symbol_key) {
321
- return Ok(value);
322
- }
323
-
324
- let string_key = ruby.str_new(name);
325
- if let Some(value) = handlers.get(string_key) {
326
- return Ok(value);
327
- }
328
-
329
- Err(Error::new(
330
- ruby.exception_name_error(),
331
- format!("Handler '{name}' not provided"),
332
- ))
333
- }
334
-
335
- /// Get an optional keyword argument from a Ruby Hash.
336
- pub fn get_kw(ruby: &Ruby, hash: RHash, name: &str) -> Option<Value> {
337
- let sym = ruby.intern(name);
338
- hash.get(sym).or_else(|| hash.get(name))
339
- }
340
-
341
- /// Parse request configuration from a Ruby options Hash.
342
- ///
343
- /// Supports: query, headers, cookies, json, data, raw_body, files
344
- pub fn parse_request_config(ruby: &Ruby, options: Value) -> Result<RequestConfig, Error> {
345
- if options.is_nil() {
346
- return Ok(RequestConfig {
347
- query: None,
348
- headers: HashMap::new(),
349
- cookies: HashMap::new(),
350
- body: None,
351
- });
352
- }
353
-
354
- let hash = RHash::from_value(options)
355
- .ok_or_else(|| Error::new(ruby.exception_arg_error(), "request options must be a Hash"))?;
356
-
357
- let json_module = ruby
358
- .class_object()
359
- .const_get("JSON")
360
- .map_err(|_| Error::new(ruby.exception_runtime_error(), "JSON module not available"))?;
361
-
362
- let query = if let Some(value) = get_kw(ruby, hash, "query") {
363
- if value.is_nil() {
364
- None
365
- } else {
366
- Some(ruby_value_to_json(ruby, json_module, value)?)
367
- }
368
- } else {
369
- None
370
- };
371
-
372
- let headers = if let Some(value) = get_kw(ruby, hash, "headers") {
373
- if value.is_nil() {
374
- HashMap::new()
375
- } else {
376
- let hash = RHash::try_convert(value)?;
377
- hash.to_hash_map::<String, String>()?
378
- }
379
- } else {
380
- HashMap::new()
381
- };
382
-
383
- let cookies = if let Some(value) = get_kw(ruby, hash, "cookies") {
384
- if value.is_nil() {
385
- HashMap::new()
386
- } else {
387
- let hash = RHash::try_convert(value)?;
388
- hash.to_hash_map::<String, String>()?
389
- }
390
- } else {
391
- HashMap::new()
392
- };
393
-
394
- let files_opt = get_kw(ruby, hash, "files");
395
- let has_files = files_opt.as_ref().is_some_and(|f| !f.is_nil());
396
-
397
- let body = if has_files {
398
- let files_value = files_opt.ok_or_else(|| {
399
- Error::new(
400
- ruby.exception_runtime_error(),
401
- "Files option should be Some if has_files is true",
402
- )
403
- })?;
404
- let files = extract_files(ruby, files_value)?;
405
-
406
- let mut form_data = Vec::new();
407
- if let Some(data_value) = get_kw(ruby, hash, "data")
408
- && !data_value.is_nil()
409
- {
410
- let data_hash = RHash::try_convert(data_value)?;
411
-
412
- let keys_array: RArray = data_hash.funcall("keys", ())?;
413
-
414
- for i in 0..keys_array.len() {
415
- let key_val = keys_array.entry::<Value>(i as isize)?;
416
- let field_name = String::try_convert(key_val)?;
417
- let value = data_hash
418
- .get(key_val)
419
- .ok_or_else(|| Error::new(ruby.exception_runtime_error(), "Failed to get hash value"))?;
420
-
421
- if let Some(array) = RArray::from_value(value) {
422
- for j in 0..array.len() {
423
- let item = array.entry::<Value>(j as isize)?;
424
- let item_str = String::try_convert(item)?;
425
- form_data.push((field_name.clone(), item_str));
426
- }
427
- } else {
428
- let value_str = String::try_convert(value)?;
429
- form_data.push((field_name, value_str));
430
- }
431
- }
432
- }
433
-
434
- Some(RequestBody::Multipart { form_data, files })
435
- } else if let Some(value) = get_kw(ruby, hash, "json") {
436
- if value.is_nil() {
437
- None
438
- } else {
439
- Some(RequestBody::Json(ruby_value_to_json(ruby, json_module, value)?))
440
- }
441
- } else if let Some(value) = get_kw(ruby, hash, "data") {
442
- if value.is_nil() {
443
- None
444
- } else {
445
- Some(RequestBody::Form(ruby_value_to_json(ruby, json_module, value)?))
446
- }
447
- } else if let Some(value) = get_kw(ruby, hash, "raw_body") {
448
- if value.is_nil() {
449
- None
450
- } else {
451
- Some(RequestBody::Raw(String::try_convert(value)?))
452
- }
453
- } else {
454
- None
455
- };
456
-
457
- Ok(RequestConfig {
458
- query,
459
- headers,
460
- cookies,
461
- body,
462
- })
463
- }
464
-
465
- /// Extract files from a Ruby Hash.
466
- ///
467
- /// Files can be provided as [filename, content] or [filename, content, content_type]
468
- pub fn extract_files(ruby: &Ruby, files_value: Value) -> Result<Vec<MultipartFilePart>, Error> {
469
- let files_hash = RHash::try_convert(files_value)?;
470
-
471
- let keys_array: RArray = files_hash.funcall("keys", ())?;
472
- let mut result = Vec::new();
473
-
474
- for i in 0..keys_array.len() {
475
- let key_val = keys_array.entry::<Value>(i as isize)?;
476
- let field_name = String::try_convert(key_val)?;
477
- let value = files_hash
478
- .get(key_val)
479
- .ok_or_else(|| Error::new(ruby.exception_runtime_error(), "Failed to get hash value"))?;
480
-
481
- if let Some(outer_array) = RArray::from_value(value) {
482
- if outer_array.is_empty() {
483
- continue;
484
- }
485
-
486
- let first_elem = outer_array.entry::<Value>(0)?;
487
-
488
- if RArray::from_value(first_elem).is_some() {
489
- for j in 0..outer_array.len() {
490
- let file_array = outer_array.entry::<Value>(j as isize)?;
491
- let file_data = extract_single_file(ruby, &field_name, file_array)?;
492
- result.push(file_data);
493
- }
494
- } else {
495
- let file_data = extract_single_file(ruby, &field_name, value)?;
496
- result.push(file_data);
497
- }
498
- }
499
- }
500
-
501
- Ok(result)
502
- }
503
-
504
- /// Extract a single file from a Ruby array [filename, content, content_type (optional)].
505
- pub fn extract_single_file(ruby: &Ruby, field_name: &str, array_value: Value) -> Result<MultipartFilePart, Error> {
506
- let array = RArray::from_value(array_value)
507
- .ok_or_else(|| Error::new(ruby.exception_arg_error(), "file must be an Array [filename, content]"))?;
508
-
509
- if array.len() < 2 {
510
- return Err(Error::new(
511
- ruby.exception_arg_error(),
512
- "file Array must have at least 2 elements: [filename, content]",
513
- ));
514
- }
515
-
516
- let filename: String = String::try_convert(array.shift()?)?;
517
- let content_str: String = String::try_convert(array.shift()?)?;
518
- let content = content_str.into_bytes();
519
-
520
- let content_type: Option<String> = if !array.is_empty() {
521
- String::try_convert(array.shift()?).ok()
522
- } else {
523
- None
524
- };
525
-
526
- Ok(MultipartFilePart {
527
- field_name: field_name.to_string(),
528
- filename,
529
- content,
530
- content_type,
531
- })
532
- }
533
-
534
- /// Extract an optional string from a Ruby Hash.
535
- pub fn get_optional_string_from_hash(hash: RHash, key: &str) -> Result<Option<String>, Error> {
536
- match hash.get(String::from(key)) {
537
- Some(v) if !v.is_nil() => Ok(Some(String::try_convert(v)?)),
538
- _ => Ok(None),
539
- }
540
- }
541
-
542
- /// Extract a required string from a Ruby Hash.
543
- pub fn get_required_string_from_hash(hash: RHash, key: &str, ruby: &Ruby) -> Result<String, Error> {
544
- let value = hash
545
- .get(String::from(key))
546
- .ok_or_else(|| Error::new(ruby.exception_arg_error(), format!("missing required key '{}'", key)))?;
547
- if value.is_nil() {
548
- return Err(Error::new(
549
- ruby.exception_arg_error(),
550
- format!("key '{}' cannot be nil", key),
551
- ));
552
- }
553
- String::try_convert(value)
554
- }
1
+ //! Ruby ↔ Rust type conversion utilities.
2
+ //!
3
+ //! This module provides functions for converting between Ruby and Rust types,
4
+ //! including JSON conversion, string conversion, and request/response building.
5
+
6
+ #![allow(dead_code)]
7
+ #![deny(clippy::unwrap_used)]
8
+
9
+ use bytes::Bytes;
10
+ use magnus::prelude::*;
11
+ use magnus::{Error, RArray, RHash, RString, Ruby, Symbol, TryConvert, Value};
12
+ use serde_json::Value as JsonValue;
13
+ use spikard_core::problem::ProblemDetails;
14
+ use spikard_http::testing::MultipartFilePart;
15
+ use std::collections::HashMap;
16
+
17
+ use crate::testing::client::{RequestBody, RequestConfig, TestResponseData};
18
+
19
+ /// Convert a Ruby value to JSON.
20
+ ///
21
+ /// Fast-path converts common Ruby types directly in Rust to avoid
22
+ /// `JSON.generate` + `serde_json::from_str` overhead.
23
+ ///
24
+ /// Falls back to Ruby JSON for unsupported types to preserve behavior.
25
+ pub fn ruby_value_to_json(ruby: &Ruby, json_module: Value, value: Value) -> Result<JsonValue, Error> {
26
+ if value.is_nil() {
27
+ return Ok(JsonValue::Null);
28
+ }
29
+
30
+ if let Some(converted) = ruby_value_to_json_fast(ruby, json_module, value, 0)? {
31
+ return Ok(converted);
32
+ }
33
+
34
+ ruby_value_to_json_fallback(ruby, json_module, value)
35
+ }
36
+
37
+ fn ruby_value_to_json_fallback(ruby: &Ruby, json_module: Value, value: Value) -> Result<JsonValue, Error> {
38
+ let json_string: String = json_module.funcall("generate", (value,))?;
39
+ serde_json::from_str(&json_string).map_err(|err| {
40
+ Error::new(
41
+ ruby.exception_runtime_error(),
42
+ format!("Failed to convert Ruby value to JSON: {err}"),
43
+ )
44
+ })
45
+ }
46
+
47
+ fn ruby_value_to_json_fast(
48
+ ruby: &Ruby,
49
+ json_module: Value,
50
+ value: Value,
51
+ depth: usize,
52
+ ) -> Result<Option<JsonValue>, Error> {
53
+ // Cycle detection is non-trivial without tracking Ruby object IDs; a shallow
54
+ // recursion guard avoids worst-case behavior and defers to Ruby JSON.
55
+ if depth > 64 {
56
+ return Ok(None);
57
+ }
58
+
59
+ if value.is_nil() {
60
+ return Ok(Some(JsonValue::Null));
61
+ }
62
+
63
+ if value.is_kind_of(ruby.class_true_class()) {
64
+ return Ok(Some(JsonValue::Bool(true)));
65
+ }
66
+
67
+ if value.is_kind_of(ruby.class_false_class()) {
68
+ return Ok(Some(JsonValue::Bool(false)));
69
+ }
70
+
71
+ if let Ok(text) = RString::try_convert(value) {
72
+ let slice = unsafe { text.as_slice() };
73
+ return Ok(Some(JsonValue::String(String::from_utf8_lossy(slice).to_string())));
74
+ }
75
+
76
+ if value.is_kind_of(ruby.class_float()) {
77
+ let n = f64::try_convert(value)?;
78
+ let number = serde_json::Number::from_f64(n).ok_or_else(|| {
79
+ Error::new(
80
+ ruby.exception_runtime_error(),
81
+ "Failed to convert Ruby Float to JSON number",
82
+ )
83
+ })?;
84
+ return Ok(Some(JsonValue::Number(number)));
85
+ }
86
+
87
+ if value.is_kind_of(ruby.class_integer()) {
88
+ if let Ok(n) = i64::try_convert(value) {
89
+ return Ok(Some(JsonValue::from(n)));
90
+ }
91
+ if let Ok(n) = u64::try_convert(value) {
92
+ return Ok(Some(JsonValue::from(n)));
93
+ }
94
+ }
95
+
96
+ if let Some(array) = RArray::from_value(value) {
97
+ let mut out = Vec::with_capacity(array.len());
98
+ for idx in 0..array.len() {
99
+ let item: Value = array.entry(idx as isize)?;
100
+ let json_item = match ruby_value_to_json_fast(ruby, json_module, item, depth + 1)? {
101
+ Some(v) => v,
102
+ None => ruby_value_to_json_fallback(ruby, json_module, item)?,
103
+ };
104
+ out.push(json_item);
105
+ }
106
+ return Ok(Some(JsonValue::Array(out)));
107
+ }
108
+
109
+ if let Some(hash) = RHash::from_value(value) {
110
+ let mut map = serde_json::Map::with_capacity(hash.len());
111
+ hash.foreach(|key: Value, val: Value| {
112
+ let key_str = if let Ok(key_text) = RString::try_convert(key) {
113
+ let slice = unsafe { key_text.as_slice() };
114
+ String::from_utf8_lossy(slice).to_string()
115
+ } else if let Ok(sym) = Symbol::try_convert(key) {
116
+ sym.name()?.into_owned()
117
+ } else {
118
+ let key_as_str: String = key.funcall("to_s", ())?;
119
+ key_as_str
120
+ };
121
+
122
+ let json_val = match ruby_value_to_json_fast(ruby, json_module, val, depth + 1)? {
123
+ Some(v) => v,
124
+ None => ruby_value_to_json_fallback(ruby, json_module, val)?,
125
+ };
126
+
127
+ map.insert(key_str, json_val);
128
+ Ok(magnus::r_hash::ForEach::Continue)
129
+ })?;
130
+ return Ok(Some(JsonValue::Object(map)));
131
+ }
132
+
133
+ Ok(None)
134
+ }
135
+
136
+ /// Convert JSON to a Ruby value.
137
+ ///
138
+ /// Recursively converts JSON types to native Ruby types:
139
+ /// - null → nil
140
+ /// - bool → true/false
141
+ /// - number → integer or float
142
+ /// - string → string
143
+ /// - array → array
144
+ /// - object → hash
145
+ pub fn json_to_ruby(ruby: &Ruby, value: &JsonValue) -> Result<Value, Error> {
146
+ json_to_ruby_with_uploads(ruby, value, None::<&Value>)
147
+ }
148
+
149
+ /// Convert JSON to a Ruby value, optionally materialising UploadFile objects.
150
+ ///
151
+ /// If `upload_file_class` is provided and the JSON object contains
152
+ /// file-metadata keys (`filename`, `content`), this will instantiate
153
+ /// `UploadFile` instead of returning a plain Hash.
154
+ pub fn json_to_ruby_with_uploads(
155
+ ruby: &Ruby,
156
+ value: &JsonValue,
157
+ upload_file_class: Option<&Value>,
158
+ ) -> Result<Value, Error> {
159
+ match value {
160
+ JsonValue::Null => Ok(ruby.qnil().as_value()),
161
+ JsonValue::Bool(b) => Ok(if *b {
162
+ ruby.qtrue().as_value()
163
+ } else {
164
+ ruby.qfalse().as_value()
165
+ }),
166
+ JsonValue::Number(num) => {
167
+ if let Some(i) = num.as_i64() {
168
+ Ok(ruby.integer_from_i64(i).as_value())
169
+ } else if let Some(f) = num.as_f64() {
170
+ Ok(ruby.float_from_f64(f).as_value())
171
+ } else {
172
+ Ok(ruby.qnil().as_value())
173
+ }
174
+ }
175
+ JsonValue::String(str_val) => Ok(ruby.str_new(str_val).as_value()),
176
+ JsonValue::Array(items) => {
177
+ let array = ruby.ary_new_capa(items.len());
178
+ for item in items {
179
+ array.push(json_to_ruby_with_uploads(ruby, item, upload_file_class)?)?;
180
+ }
181
+ Ok(array.as_value())
182
+ }
183
+ JsonValue::Object(map) => {
184
+ if let Some(upload_file) = upload_file_class
185
+ && let Some(upload) = try_build_upload_file(ruby, upload_file, map)?
186
+ {
187
+ return Ok(upload);
188
+ }
189
+
190
+ let hash = ruby.hash_new_capa(map.len());
191
+ for (key, item) in map {
192
+ hash.aset(
193
+ ruby.str_new(key),
194
+ json_to_ruby_with_uploads(ruby, item, upload_file_class)?,
195
+ )?;
196
+ }
197
+ Ok(hash.as_value())
198
+ }
199
+ }
200
+ }
201
+
202
+ /// Convert a HashMap to a Ruby Hash.
203
+ pub fn map_to_ruby_hash(ruby: &Ruby, map: &HashMap<String, String>) -> Result<Value, Error> {
204
+ let hash = ruby.hash_new_capa(map.len());
205
+ for (key, value) in map {
206
+ hash.aset(ruby.str_new(key), ruby.str_new(value))?;
207
+ }
208
+ Ok(hash.as_value())
209
+ }
210
+
211
+ /// Convert a HashMap of Vecs to a Ruby Hash with array values.
212
+ pub fn multimap_to_ruby_hash(ruby: &Ruby, map: &HashMap<String, Vec<String>>) -> Result<Value, Error> {
213
+ let hash = ruby.hash_new_capa(map.len());
214
+ for (key, values) in map {
215
+ let array = ruby.ary_new_capa(values.len());
216
+ for value in values {
217
+ array.push(ruby.str_new(value))?;
218
+ }
219
+ hash.aset(ruby.str_new(key), array)?;
220
+ }
221
+ Ok(hash.as_value())
222
+ }
223
+
224
+ fn try_build_upload_file(
225
+ ruby: &Ruby,
226
+ upload_file_class: &Value,
227
+ map: &serde_json::Map<String, JsonValue>,
228
+ ) -> Result<Option<Value>, Error> {
229
+ let filename = match map.get("filename").and_then(|v| v.as_str()) {
230
+ Some(name) => name,
231
+ None => return Ok(None),
232
+ };
233
+ let content = match map.get("content") {
234
+ Some(JsonValue::String(s)) => s.as_str(),
235
+ _ => return Ok(None),
236
+ };
237
+
238
+ let content_type = map.get("content_type").and_then(|v| v.as_str());
239
+ let size = map.get("size").and_then(|v| v.as_u64());
240
+ let headers_value = map
241
+ .get("headers")
242
+ .and_then(|v| v.as_object())
243
+ .map(|obj| {
244
+ obj.iter()
245
+ .filter_map(|(k, v)| v.as_str().map(|val| (k.clone(), val.to_string())))
246
+ .collect::<HashMap<String, String>>()
247
+ })
248
+ .unwrap_or_default();
249
+ let headers = map_to_ruby_hash(ruby, &headers_value)?;
250
+ let content_encoding = map.get("content_encoding").and_then(|v| v.as_str());
251
+
252
+ let kwargs = magnus::kwargs!(
253
+ "content_type" => content_type,
254
+ "size" => size,
255
+ "headers" => headers,
256
+ "content_encoding" => content_encoding
257
+ );
258
+
259
+ let upload = upload_file_class.funcall("new", (filename, content, kwargs))?;
260
+ Ok(Some(upload))
261
+ }
262
+
263
+ /// Convert a Ruby value to Bytes.
264
+ ///
265
+ /// Accepts either String or Array of bytes.
266
+ pub fn ruby_value_to_bytes(value: Value) -> Result<Bytes, std::io::Error> {
267
+ if let Ok(str_value) = RString::try_convert(value) {
268
+ let slice = unsafe { str_value.as_slice() };
269
+ return Ok(Bytes::copy_from_slice(slice));
270
+ }
271
+
272
+ if let Ok(vec_bytes) = Vec::<u8>::try_convert(value) {
273
+ return Ok(Bytes::from(vec_bytes));
274
+ }
275
+
276
+ Err(std::io::Error::other(
277
+ "Streaming chunks must be Strings or Arrays of bytes",
278
+ ))
279
+ }
280
+
281
+ /// Convert a response to a Ruby Hash.
282
+ pub fn response_to_ruby(ruby: &Ruby, response: TestResponseData) -> Result<Value, Error> {
283
+ let hash = ruby.hash_new();
284
+
285
+ hash.aset(
286
+ ruby.intern("status_code"),
287
+ ruby.integer_from_i64(response.status as i64),
288
+ )?;
289
+
290
+ let headers_hash = ruby.hash_new();
291
+ for (key, value) in response.headers {
292
+ headers_hash.aset(ruby.str_new(&key), ruby.str_new(&value))?;
293
+ }
294
+ hash.aset(ruby.intern("headers"), headers_hash)?;
295
+
296
+ if let Some(body) = response.body_text {
297
+ let body_value = ruby.str_new(&body);
298
+ hash.aset(ruby.intern("body"), body_value)?;
299
+ hash.aset(ruby.intern("body_text"), body_value)?;
300
+ } else {
301
+ hash.aset(ruby.intern("body"), ruby.qnil())?;
302
+ hash.aset(ruby.intern("body_text"), ruby.qnil())?;
303
+ }
304
+
305
+ Ok(hash.as_value())
306
+ }
307
+
308
+ /// Convert a ProblemDetails to a JSON string.
309
+ pub fn problem_to_json(problem: &ProblemDetails) -> String {
310
+ problem
311
+ .to_json_pretty()
312
+ .unwrap_or_else(|err| format!("Failed to serialise problem details: {err}"))
313
+ }
314
+
315
+ /// Fetch a handler from a Ruby Hash by name.
316
+ ///
317
+ /// Tries both symbol and string keys.
318
+ pub fn fetch_handler(ruby: &Ruby, handlers: &RHash, name: &str) -> Result<Value, Error> {
319
+ let symbol_key = ruby.intern(name);
320
+ if let Some(value) = handlers.get(symbol_key) {
321
+ return Ok(value);
322
+ }
323
+
324
+ let string_key = ruby.str_new(name);
325
+ if let Some(value) = handlers.get(string_key) {
326
+ return Ok(value);
327
+ }
328
+
329
+ Err(Error::new(
330
+ ruby.exception_name_error(),
331
+ format!("Handler '{name}' not provided"),
332
+ ))
333
+ }
334
+
335
+ /// Get an optional keyword argument from a Ruby Hash.
336
+ pub fn get_kw(ruby: &Ruby, hash: RHash, name: &str) -> Option<Value> {
337
+ let sym = ruby.intern(name);
338
+ hash.get(sym).or_else(|| hash.get(name))
339
+ }
340
+
341
+ /// Parse request configuration from a Ruby options Hash.
342
+ ///
343
+ /// Supports: query, headers, cookies, json, data, raw_body, files
344
+ pub fn parse_request_config(ruby: &Ruby, options: Value) -> Result<RequestConfig, Error> {
345
+ if options.is_nil() {
346
+ return Ok(RequestConfig {
347
+ query: None,
348
+ headers: HashMap::new(),
349
+ cookies: HashMap::new(),
350
+ body: None,
351
+ });
352
+ }
353
+
354
+ let hash = RHash::from_value(options)
355
+ .ok_or_else(|| Error::new(ruby.exception_arg_error(), "request options must be a Hash"))?;
356
+
357
+ let json_module = ruby
358
+ .class_object()
359
+ .const_get("JSON")
360
+ .map_err(|_| Error::new(ruby.exception_runtime_error(), "JSON module not available"))?;
361
+
362
+ let query = if let Some(value) = get_kw(ruby, hash, "query") {
363
+ if value.is_nil() {
364
+ None
365
+ } else {
366
+ Some(ruby_value_to_json(ruby, json_module, value)?)
367
+ }
368
+ } else {
369
+ None
370
+ };
371
+
372
+ let headers = if let Some(value) = get_kw(ruby, hash, "headers") {
373
+ if value.is_nil() {
374
+ HashMap::new()
375
+ } else {
376
+ let hash = RHash::try_convert(value)?;
377
+ hash.to_hash_map::<String, String>()?
378
+ }
379
+ } else {
380
+ HashMap::new()
381
+ };
382
+
383
+ let cookies = if let Some(value) = get_kw(ruby, hash, "cookies") {
384
+ if value.is_nil() {
385
+ HashMap::new()
386
+ } else {
387
+ let hash = RHash::try_convert(value)?;
388
+ hash.to_hash_map::<String, String>()?
389
+ }
390
+ } else {
391
+ HashMap::new()
392
+ };
393
+
394
+ let files_opt = get_kw(ruby, hash, "files");
395
+ let has_files = files_opt.as_ref().is_some_and(|f| !f.is_nil());
396
+
397
+ let body = if has_files {
398
+ let files_value = files_opt.ok_or_else(|| {
399
+ Error::new(
400
+ ruby.exception_runtime_error(),
401
+ "Files option should be Some if has_files is true",
402
+ )
403
+ })?;
404
+ let files = extract_files(ruby, files_value)?;
405
+
406
+ let mut form_data = Vec::new();
407
+ if let Some(data_value) = get_kw(ruby, hash, "data")
408
+ && !data_value.is_nil()
409
+ {
410
+ let data_hash = RHash::try_convert(data_value)?;
411
+
412
+ let keys_array: RArray = data_hash.funcall("keys", ())?;
413
+
414
+ for i in 0..keys_array.len() {
415
+ let key_val = keys_array.entry::<Value>(i as isize)?;
416
+ let field_name = String::try_convert(key_val)?;
417
+ let value = data_hash
418
+ .get(key_val)
419
+ .ok_or_else(|| Error::new(ruby.exception_runtime_error(), "Failed to get hash value"))?;
420
+
421
+ if let Some(array) = RArray::from_value(value) {
422
+ for j in 0..array.len() {
423
+ let item = array.entry::<Value>(j as isize)?;
424
+ let item_str = String::try_convert(item)?;
425
+ form_data.push((field_name.clone(), item_str));
426
+ }
427
+ } else {
428
+ let value_str = String::try_convert(value)?;
429
+ form_data.push((field_name, value_str));
430
+ }
431
+ }
432
+ }
433
+
434
+ Some(RequestBody::Multipart { form_data, files })
435
+ } else if let Some(value) = get_kw(ruby, hash, "json") {
436
+ if value.is_nil() {
437
+ None
438
+ } else {
439
+ Some(RequestBody::Json(ruby_value_to_json(ruby, json_module, value)?))
440
+ }
441
+ } else if let Some(value) = get_kw(ruby, hash, "data") {
442
+ if value.is_nil() {
443
+ None
444
+ } else {
445
+ Some(RequestBody::Form(ruby_value_to_json(ruby, json_module, value)?))
446
+ }
447
+ } else if let Some(value) = get_kw(ruby, hash, "raw_body") {
448
+ if value.is_nil() {
449
+ None
450
+ } else {
451
+ Some(RequestBody::Raw(String::try_convert(value)?))
452
+ }
453
+ } else {
454
+ None
455
+ };
456
+
457
+ Ok(RequestConfig {
458
+ query,
459
+ headers,
460
+ cookies,
461
+ body,
462
+ })
463
+ }
464
+
465
+ /// Extract files from a Ruby Hash.
466
+ ///
467
+ /// Files can be provided as [filename, content] or [filename, content, content_type]
468
+ pub fn extract_files(ruby: &Ruby, files_value: Value) -> Result<Vec<MultipartFilePart>, Error> {
469
+ let files_hash = RHash::try_convert(files_value)?;
470
+
471
+ let keys_array: RArray = files_hash.funcall("keys", ())?;
472
+ let mut result = Vec::new();
473
+
474
+ for i in 0..keys_array.len() {
475
+ let key_val = keys_array.entry::<Value>(i as isize)?;
476
+ let field_name = String::try_convert(key_val)?;
477
+ let value = files_hash
478
+ .get(key_val)
479
+ .ok_or_else(|| Error::new(ruby.exception_runtime_error(), "Failed to get hash value"))?;
480
+
481
+ if let Some(outer_array) = RArray::from_value(value) {
482
+ if outer_array.is_empty() {
483
+ continue;
484
+ }
485
+
486
+ let first_elem = outer_array.entry::<Value>(0)?;
487
+
488
+ if RArray::from_value(first_elem).is_some() {
489
+ for j in 0..outer_array.len() {
490
+ let file_array = outer_array.entry::<Value>(j as isize)?;
491
+ let file_data = extract_single_file(ruby, &field_name, file_array)?;
492
+ result.push(file_data);
493
+ }
494
+ } else {
495
+ let file_data = extract_single_file(ruby, &field_name, value)?;
496
+ result.push(file_data);
497
+ }
498
+ }
499
+ }
500
+
501
+ Ok(result)
502
+ }
503
+
504
+ /// Extract a single file from a Ruby array [filename, content, content_type (optional)].
505
+ pub fn extract_single_file(ruby: &Ruby, field_name: &str, array_value: Value) -> Result<MultipartFilePart, Error> {
506
+ let array = RArray::from_value(array_value)
507
+ .ok_or_else(|| Error::new(ruby.exception_arg_error(), "file must be an Array [filename, content]"))?;
508
+
509
+ if array.len() < 2 {
510
+ return Err(Error::new(
511
+ ruby.exception_arg_error(),
512
+ "file Array must have at least 2 elements: [filename, content]",
513
+ ));
514
+ }
515
+
516
+ let filename: String = String::try_convert(array.shift()?)?;
517
+ let content_str: String = String::try_convert(array.shift()?)?;
518
+ let content = content_str.into_bytes();
519
+
520
+ let content_type: Option<String> = if !array.is_empty() {
521
+ String::try_convert(array.shift()?).ok()
522
+ } else {
523
+ None
524
+ };
525
+
526
+ Ok(MultipartFilePart {
527
+ field_name: field_name.to_string(),
528
+ filename,
529
+ content,
530
+ content_type,
531
+ })
532
+ }
533
+
534
+ /// Extract an optional string from a Ruby Hash.
535
+ pub fn get_optional_string_from_hash(hash: RHash, key: &str) -> Result<Option<String>, Error> {
536
+ match hash.get(String::from(key)) {
537
+ Some(v) if !v.is_nil() => Ok(Some(String::try_convert(v)?)),
538
+ _ => Ok(None),
539
+ }
540
+ }
541
+
542
+ /// Extract a required string from a Ruby Hash.
543
+ pub fn get_required_string_from_hash(hash: RHash, key: &str, ruby: &Ruby) -> Result<String, Error> {
544
+ let value = hash
545
+ .get(String::from(key))
546
+ .ok_or_else(|| Error::new(ruby.exception_arg_error(), format!("missing required key '{}'", key)))?;
547
+ if value.is_nil() {
548
+ return Err(Error::new(
549
+ ruby.exception_arg_error(),
550
+ format!("key '{}' cannot be nil", key),
551
+ ));
552
+ }
553
+ String::try_convert(value)
554
+ }