spikard 0.3.5 → 0.5.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.
Files changed (142) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +1 -1
  3. data/README.md +674 -659
  4. data/ext/spikard_rb/Cargo.toml +17 -17
  5. data/ext/spikard_rb/extconf.rb +10 -10
  6. data/ext/spikard_rb/src/lib.rs +6 -6
  7. data/lib/spikard/app.rb +405 -386
  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 -221
  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 -360
  23. data/vendor/crates/spikard-bindings-shared/Cargo.toml +63 -0
  24. data/vendor/crates/spikard-bindings-shared/examples/config_extraction.rs +132 -0
  25. data/vendor/crates/spikard-bindings-shared/src/config_extractor.rs +752 -0
  26. data/vendor/crates/spikard-bindings-shared/src/conversion_traits.rs +194 -0
  27. data/vendor/crates/spikard-bindings-shared/src/di_traits.rs +246 -0
  28. data/vendor/crates/spikard-bindings-shared/src/error_response.rs +401 -0
  29. data/vendor/crates/spikard-bindings-shared/src/handler_base.rs +238 -0
  30. data/vendor/crates/spikard-bindings-shared/src/lib.rs +24 -0
  31. data/vendor/crates/spikard-bindings-shared/src/lifecycle_base.rs +292 -0
  32. data/vendor/crates/spikard-bindings-shared/src/lifecycle_executor.rs +616 -0
  33. data/vendor/crates/spikard-bindings-shared/src/response_builder.rs +305 -0
  34. data/vendor/crates/spikard-bindings-shared/src/test_client_base.rs +248 -0
  35. data/vendor/crates/spikard-bindings-shared/src/validation_helpers.rs +351 -0
  36. data/vendor/crates/spikard-bindings-shared/tests/comprehensive_coverage.rs +454 -0
  37. data/vendor/crates/spikard-bindings-shared/tests/error_response_edge_cases.rs +383 -0
  38. data/vendor/crates/spikard-bindings-shared/tests/handler_base_integration.rs +280 -0
  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 -63
  43. data/vendor/crates/spikard-core/src/di/container.rs +702 -726
  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 -538
  47. data/vendor/crates/spikard-core/src/di/graph.rs +506 -545
  48. data/vendor/crates/spikard-core/src/di/mod.rs +192 -192
  49. data/vendor/crates/spikard-core/src/di/resolved.rs +405 -411
  50. data/vendor/crates/spikard-core/src/di/value.rs +281 -283
  51. data/vendor/crates/spikard-core/src/errors.rs +69 -39
  52. data/vendor/crates/spikard-core/src/http.rs +415 -153
  53. data/vendor/crates/spikard-core/src/lib.rs +29 -29
  54. data/vendor/crates/spikard-core/src/lifecycle.rs +1186 -422
  55. data/vendor/crates/spikard-core/src/metadata.rs +389 -0
  56. data/vendor/crates/spikard-core/src/parameters.rs +2525 -722
  57. data/vendor/crates/spikard-core/src/problem.rs +344 -310
  58. data/vendor/crates/spikard-core/src/request_data.rs +1154 -189
  59. data/vendor/crates/spikard-core/src/router.rs +510 -249
  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 +688 -0
  63. data/vendor/crates/spikard-core/src/{validation.rs → validation/mod.rs} +457 -699
  64. data/vendor/crates/spikard-http/Cargo.toml +64 -68
  65. data/vendor/crates/spikard-http/examples/sse-notifications.rs +148 -0
  66. data/vendor/crates/spikard-http/examples/websocket-chat.rs +92 -0
  67. data/vendor/crates/spikard-http/src/auth.rs +296 -247
  68. data/vendor/crates/spikard-http/src/background.rs +1860 -249
  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 -490
  73. data/vendor/crates/spikard-http/src/debug.rs +128 -63
  74. data/vendor/crates/spikard-http/src/di_handler.rs +1668 -423
  75. data/vendor/crates/spikard-http/src/handler_response.rs +901 -190
  76. data/vendor/crates/spikard-http/src/handler_trait.rs +830 -228
  77. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +290 -284
  78. data/vendor/crates/spikard-http/src/lib.rs +534 -529
  79. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +230 -149
  80. data/vendor/crates/spikard-http/src/lifecycle.rs +1193 -428
  81. data/vendor/crates/spikard-http/src/middleware/mod.rs +540 -285
  82. data/vendor/crates/spikard-http/src/middleware/multipart.rs +912 -86
  83. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +513 -147
  84. data/vendor/crates/spikard-http/src/middleware/validation.rs +735 -287
  85. data/vendor/crates/spikard-http/src/openapi/mod.rs +309 -309
  86. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +535 -190
  87. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +1363 -308
  88. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +665 -195
  89. data/vendor/crates/spikard-http/src/query_parser.rs +793 -369
  90. data/vendor/crates/spikard-http/src/response.rs +720 -399
  91. data/vendor/crates/spikard-http/src/server/handler.rs +1650 -87
  92. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +234 -98
  93. data/vendor/crates/spikard-http/src/server/mod.rs +1502 -805
  94. data/vendor/crates/spikard-http/src/server/request_extraction.rs +770 -119
  95. data/vendor/crates/spikard-http/src/server/routing_factory.rs +599 -0
  96. data/vendor/crates/spikard-http/src/sse.rs +1409 -447
  97. data/vendor/crates/spikard-http/src/testing/form.rs +52 -14
  98. data/vendor/crates/spikard-http/src/testing/multipart.rs +60 -60
  99. data/vendor/crates/spikard-http/src/testing/test_client.rs +283 -285
  100. data/vendor/crates/spikard-http/src/testing.rs +377 -377
  101. data/vendor/crates/spikard-http/src/websocket.rs +1375 -324
  102. data/vendor/crates/spikard-http/tests/background_behavior.rs +832 -0
  103. data/vendor/crates/spikard-http/tests/common/handlers.rs +309 -0
  104. data/vendor/crates/spikard-http/tests/common/mod.rs +26 -0
  105. data/vendor/crates/spikard-http/tests/di_integration.rs +192 -0
  106. data/vendor/crates/spikard-http/tests/doc_snippets.rs +5 -0
  107. data/vendor/crates/spikard-http/tests/lifecycle_execution.rs +1093 -0
  108. data/vendor/crates/spikard-http/tests/multipart_behavior.rs +656 -0
  109. data/vendor/crates/spikard-http/tests/server_config_builder.rs +314 -0
  110. data/vendor/crates/spikard-http/tests/sse_behavior.rs +620 -0
  111. data/vendor/crates/spikard-http/tests/websocket_behavior.rs +663 -0
  112. data/vendor/crates/spikard-rb/Cargo.toml +48 -42
  113. data/vendor/crates/spikard-rb/build.rs +199 -8
  114. data/vendor/crates/spikard-rb/src/background.rs +63 -63
  115. data/vendor/crates/spikard-rb/src/config/mod.rs +5 -0
  116. data/vendor/crates/spikard-rb/src/{config.rs → config/server_config.rs} +285 -294
  117. data/vendor/crates/spikard-rb/src/conversion.rs +554 -453
  118. data/vendor/crates/spikard-rb/src/di/builder.rs +100 -0
  119. data/vendor/crates/spikard-rb/src/{di.rs → di/mod.rs} +375 -409
  120. data/vendor/crates/spikard-rb/src/handler.rs +618 -625
  121. data/vendor/crates/spikard-rb/src/integration/mod.rs +3 -0
  122. data/vendor/crates/spikard-rb/src/lib.rs +1810 -2771
  123. data/vendor/crates/spikard-rb/src/lifecycle.rs +275 -274
  124. data/vendor/crates/spikard-rb/src/metadata/mod.rs +5 -0
  125. data/vendor/crates/spikard-rb/src/metadata/route_extraction.rs +447 -0
  126. data/vendor/crates/spikard-rb/src/runtime/mod.rs +5 -0
  127. data/vendor/crates/spikard-rb/src/runtime/server_runner.rs +324 -0
  128. data/vendor/crates/spikard-rb/src/server.rs +308 -283
  129. data/vendor/crates/spikard-rb/src/sse.rs +231 -231
  130. data/vendor/crates/spikard-rb/src/{test_client.rs → testing/client.rs} +551 -404
  131. data/vendor/crates/spikard-rb/src/testing/mod.rs +7 -0
  132. data/vendor/crates/spikard-rb/src/{test_sse.rs → testing/sse.rs} +143 -143
  133. data/vendor/crates/spikard-rb/src/testing/websocket.rs +635 -0
  134. data/vendor/crates/spikard-rb/src/websocket.rs +374 -233
  135. metadata +46 -13
  136. data/vendor/crates/spikard-http/src/parameters.rs +0 -1
  137. data/vendor/crates/spikard-http/src/problem.rs +0 -1
  138. data/vendor/crates/spikard-http/src/router.rs +0 -1
  139. data/vendor/crates/spikard-http/src/schema_registry.rs +0 -1
  140. data/vendor/crates/spikard-http/src/type_hints.rs +0 -1
  141. data/vendor/crates/spikard-http/src/validation.rs +0 -1
  142. data/vendor/crates/spikard-rb/src/test_websocket.rs +0 -221
@@ -1,453 +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
-
8
- use bytes::Bytes;
9
- use magnus::prelude::*;
10
- use magnus::{Error, RArray, RHash, RString, Ruby, TryConvert, Value};
11
- use serde_json::Value as JsonValue;
12
- use spikard_http::problem::ProblemDetails;
13
- use spikard_http::testing::MultipartFilePart;
14
- use std::collections::HashMap;
15
-
16
- use crate::test_client::{RequestBody, RequestConfig, TestResponseData};
17
-
18
- /// Convert a Ruby value to JSON.
19
- ///
20
- /// Uses Ruby's JSON.generate method to serialize the Ruby object
21
- /// and then parses the result.
22
- pub fn ruby_value_to_json(ruby: &Ruby, json_module: Value, value: Value) -> Result<JsonValue, Error> {
23
- if value.is_nil() {
24
- return Ok(JsonValue::Null);
25
- }
26
-
27
- let json_string: String = json_module.funcall("generate", (value,))?;
28
- serde_json::from_str(&json_string).map_err(|err| {
29
- Error::new(
30
- ruby.exception_runtime_error(),
31
- format!("Failed to convert Ruby value to JSON: {err}"),
32
- )
33
- })
34
- }
35
-
36
- /// Convert JSON to a Ruby value.
37
- ///
38
- /// Recursively converts JSON types to native Ruby types:
39
- /// - null → nil
40
- /// - bool → true/false
41
- /// - number → integer or float
42
- /// - string string
43
- /// - array → array
44
- /// - object → hash
45
- pub fn json_to_ruby(ruby: &Ruby, value: &JsonValue) -> Result<Value, Error> {
46
- json_to_ruby_with_uploads(ruby, value, None::<&Value>)
47
- }
48
-
49
- /// Convert JSON to a Ruby value, optionally materialising UploadFile objects.
50
- ///
51
- /// If `upload_file_class` is provided and the JSON object contains
52
- /// file-metadata keys (`filename`, `content`), this will instantiate
53
- /// `UploadFile` instead of returning a plain Hash.
54
- pub fn json_to_ruby_with_uploads(
55
- ruby: &Ruby,
56
- value: &JsonValue,
57
- upload_file_class: Option<&Value>,
58
- ) -> Result<Value, Error> {
59
- match value {
60
- JsonValue::Null => Ok(ruby.qnil().as_value()),
61
- JsonValue::Bool(b) => Ok(if *b {
62
- ruby.qtrue().as_value()
63
- } else {
64
- ruby.qfalse().as_value()
65
- }),
66
- JsonValue::Number(num) => {
67
- if let Some(i) = num.as_i64() {
68
- Ok(ruby.integer_from_i64(i).as_value())
69
- } else if let Some(f) = num.as_f64() {
70
- Ok(ruby.float_from_f64(f).as_value())
71
- } else {
72
- Ok(ruby.qnil().as_value())
73
- }
74
- }
75
- JsonValue::String(str_val) => Ok(ruby.str_new(str_val).as_value()),
76
- JsonValue::Array(items) => {
77
- let array = ruby.ary_new();
78
- for item in items {
79
- array.push(json_to_ruby_with_uploads(ruby, item, upload_file_class)?)?;
80
- }
81
- Ok(array.as_value())
82
- }
83
- JsonValue::Object(map) => {
84
- if let Some(upload_file) = upload_file_class {
85
- if let Some(upload) = try_build_upload_file(ruby, upload_file, map)? {
86
- return Ok(upload);
87
- }
88
- }
89
-
90
- let hash = ruby.hash_new();
91
- for (key, item) in map {
92
- hash.aset(
93
- ruby.str_new(key),
94
- json_to_ruby_with_uploads(ruby, item, upload_file_class)?,
95
- )?;
96
- }
97
- Ok(hash.as_value())
98
- }
99
- }
100
- }
101
-
102
- /// Convert a HashMap to a Ruby Hash.
103
- pub fn map_to_ruby_hash(ruby: &Ruby, map: &HashMap<String, String>) -> Result<Value, Error> {
104
- let hash = ruby.hash_new();
105
- for (key, value) in map {
106
- hash.aset(ruby.str_new(key), ruby.str_new(value))?;
107
- }
108
- Ok(hash.as_value())
109
- }
110
-
111
- /// Convert a HashMap of Vecs to a Ruby Hash with array values.
112
- pub fn multimap_to_ruby_hash(ruby: &Ruby, map: &HashMap<String, Vec<String>>) -> Result<Value, Error> {
113
- let hash = ruby.hash_new();
114
- for (key, values) in map {
115
- let array = ruby.ary_new();
116
- for value in values {
117
- array.push(ruby.str_new(value))?;
118
- }
119
- hash.aset(ruby.str_new(key), array)?;
120
- }
121
- Ok(hash.as_value())
122
- }
123
-
124
- fn try_build_upload_file(
125
- ruby: &Ruby,
126
- upload_file_class: &Value,
127
- map: &serde_json::Map<String, JsonValue>,
128
- ) -> Result<Option<Value>, Error> {
129
- let filename = match map.get("filename").and_then(|v| v.as_str()) {
130
- Some(name) => name,
131
- None => return Ok(None),
132
- };
133
- let content = match map.get("content") {
134
- Some(JsonValue::String(s)) => s.as_str(),
135
- _ => return Ok(None),
136
- };
137
-
138
- let content_type = map.get("content_type").and_then(|v| v.as_str());
139
- let size = map.get("size").and_then(|v| v.as_u64());
140
- let headers_value = map
141
- .get("headers")
142
- .and_then(|v| v.as_object())
143
- .map(|obj| {
144
- obj.iter()
145
- .filter_map(|(k, v)| v.as_str().map(|val| (k.clone(), val.to_string())))
146
- .collect::<HashMap<String, String>>()
147
- })
148
- .unwrap_or_default();
149
- let headers = map_to_ruby_hash(ruby, &headers_value)?;
150
- let content_encoding = map.get("content_encoding").and_then(|v| v.as_str());
151
-
152
- let kwargs = magnus::kwargs!(
153
- "content_type" => content_type,
154
- "size" => size,
155
- "headers" => headers,
156
- "content_encoding" => content_encoding
157
- );
158
-
159
- let upload = upload_file_class.funcall("new", (filename, content, kwargs))?;
160
- Ok(Some(upload))
161
- }
162
-
163
- /// Convert a Ruby value to Bytes.
164
- ///
165
- /// Accepts either String or Array of bytes.
166
- pub fn ruby_value_to_bytes(value: Value) -> Result<Bytes, std::io::Error> {
167
- if let Ok(str_value) = RString::try_convert(value) {
168
- // SAFETY: Magnus guarantees RString::as_slice() returns valid UTF-8 (or binary)
169
- // bytes for the lifetime of the RString. The slice is only used within this
170
- // function scope to copy into a Bytes buffer, and does not outlive the RString
171
- // reference. The copy_from_slice operation is safe for the borrowed data.
172
- let slice = unsafe { str_value.as_slice() };
173
- return Ok(Bytes::copy_from_slice(slice));
174
- }
175
-
176
- if let Ok(vec_bytes) = Vec::<u8>::try_convert(value) {
177
- return Ok(Bytes::from(vec_bytes));
178
- }
179
-
180
- Err(std::io::Error::other(
181
- "Streaming chunks must be Strings or Arrays of bytes",
182
- ))
183
- }
184
-
185
- /// Convert a response to a Ruby Hash.
186
- pub fn response_to_ruby(ruby: &Ruby, response: TestResponseData) -> Result<Value, Error> {
187
- let hash = ruby.hash_new();
188
-
189
- hash.aset(
190
- ruby.intern("status_code"),
191
- ruby.integer_from_i64(response.status as i64),
192
- )?;
193
-
194
- let headers_hash = ruby.hash_new();
195
- for (key, value) in response.headers {
196
- headers_hash.aset(ruby.str_new(&key), ruby.str_new(&value))?;
197
- }
198
- hash.aset(ruby.intern("headers"), headers_hash)?;
199
-
200
- if let Some(body) = response.body_text {
201
- let body_value = ruby.str_new(&body);
202
- hash.aset(ruby.intern("body"), body_value)?;
203
- hash.aset(ruby.intern("body_text"), body_value)?;
204
- } else {
205
- hash.aset(ruby.intern("body"), ruby.qnil())?;
206
- hash.aset(ruby.intern("body_text"), ruby.qnil())?;
207
- }
208
-
209
- Ok(hash.as_value())
210
- }
211
-
212
- /// Convert a ProblemDetails to a JSON string.
213
- pub fn problem_to_json(problem: &ProblemDetails) -> String {
214
- problem
215
- .to_json_pretty()
216
- .unwrap_or_else(|err| format!("Failed to serialise problem details: {err}"))
217
- }
218
-
219
- /// Fetch a handler from a Ruby Hash by name.
220
- ///
221
- /// Tries both symbol and string keys.
222
- pub fn fetch_handler(ruby: &Ruby, handlers: &RHash, name: &str) -> Result<Value, Error> {
223
- let symbol_key = ruby.intern(name);
224
- if let Some(value) = handlers.get(symbol_key) {
225
- return Ok(value);
226
- }
227
-
228
- let string_key = ruby.str_new(name);
229
- if let Some(value) = handlers.get(string_key) {
230
- return Ok(value);
231
- }
232
-
233
- Err(Error::new(
234
- ruby.exception_name_error(),
235
- format!("Handler '{name}' not provided"),
236
- ))
237
- }
238
-
239
- /// Get an optional keyword argument from a Ruby Hash.
240
- pub fn get_kw(ruby: &Ruby, hash: RHash, name: &str) -> Option<Value> {
241
- let sym = ruby.intern(name);
242
- hash.get(sym).or_else(|| hash.get(name))
243
- }
244
-
245
- /// Parse request configuration from a Ruby options Hash.
246
- ///
247
- /// Supports: query, headers, cookies, json, data, raw_body, files
248
- pub fn parse_request_config(ruby: &Ruby, options: Value) -> Result<RequestConfig, Error> {
249
- if options.is_nil() {
250
- return Ok(RequestConfig {
251
- query: None,
252
- headers: HashMap::new(),
253
- cookies: HashMap::new(),
254
- body: None,
255
- });
256
- }
257
-
258
- let hash = RHash::from_value(options)
259
- .ok_or_else(|| Error::new(ruby.exception_arg_error(), "request options must be a Hash"))?;
260
-
261
- let json_module = ruby
262
- .class_object()
263
- .const_get("JSON")
264
- .map_err(|_| Error::new(ruby.exception_runtime_error(), "JSON module not available"))?;
265
-
266
- let query = if let Some(value) = get_kw(ruby, hash, "query") {
267
- if value.is_nil() {
268
- None
269
- } else {
270
- Some(ruby_value_to_json(ruby, json_module, value)?)
271
- }
272
- } else {
273
- None
274
- };
275
-
276
- let headers = if let Some(value) = get_kw(ruby, hash, "headers") {
277
- if value.is_nil() {
278
- HashMap::new()
279
- } else {
280
- let hash = RHash::try_convert(value)?;
281
- hash.to_hash_map::<String, String>()?
282
- }
283
- } else {
284
- HashMap::new()
285
- };
286
-
287
- let cookies = if let Some(value) = get_kw(ruby, hash, "cookies") {
288
- if value.is_nil() {
289
- HashMap::new()
290
- } else {
291
- let hash = RHash::try_convert(value)?;
292
- hash.to_hash_map::<String, String>()?
293
- }
294
- } else {
295
- HashMap::new()
296
- };
297
-
298
- let files_opt = get_kw(ruby, hash, "files");
299
- let has_files = files_opt.is_some() && !files_opt.unwrap().is_nil();
300
-
301
- let body = if has_files {
302
- let files_value = files_opt.unwrap();
303
- let files = extract_files(ruby, files_value)?;
304
-
305
- let mut form_data = Vec::new();
306
- if let Some(data_value) = get_kw(ruby, hash, "data")
307
- && !data_value.is_nil()
308
- {
309
- let data_hash = RHash::try_convert(data_value)?;
310
-
311
- let keys_array: RArray = data_hash.funcall("keys", ())?;
312
-
313
- for i in 0..keys_array.len() {
314
- let key_val = keys_array.entry::<Value>(i as isize)?;
315
- let field_name = String::try_convert(key_val)?;
316
- let value = data_hash
317
- .get(key_val)
318
- .ok_or_else(|| Error::new(ruby.exception_runtime_error(), "Failed to get hash value"))?;
319
-
320
- if let Some(array) = RArray::from_value(value) {
321
- for j in 0..array.len() {
322
- let item = array.entry::<Value>(j as isize)?;
323
- let item_str = String::try_convert(item)?;
324
- form_data.push((field_name.clone(), item_str));
325
- }
326
- } else {
327
- let value_str = String::try_convert(value)?;
328
- form_data.push((field_name, value_str));
329
- }
330
- }
331
- }
332
-
333
- Some(RequestBody::Multipart { form_data, files })
334
- } else if let Some(value) = get_kw(ruby, hash, "json") {
335
- if value.is_nil() {
336
- None
337
- } else {
338
- Some(RequestBody::Json(ruby_value_to_json(ruby, json_module, value)?))
339
- }
340
- } else if let Some(value) = get_kw(ruby, hash, "data") {
341
- if value.is_nil() {
342
- None
343
- } else {
344
- Some(RequestBody::Form(ruby_value_to_json(ruby, json_module, value)?))
345
- }
346
- } else if let Some(value) = get_kw(ruby, hash, "raw_body") {
347
- if value.is_nil() {
348
- None
349
- } else {
350
- Some(RequestBody::Raw(String::try_convert(value)?))
351
- }
352
- } else {
353
- None
354
- };
355
-
356
- Ok(RequestConfig {
357
- query,
358
- headers,
359
- cookies,
360
- body,
361
- })
362
- }
363
-
364
- /// Extract files from a Ruby Hash.
365
- ///
366
- /// Files can be provided as [filename, content] or [filename, content, content_type]
367
- pub fn extract_files(ruby: &Ruby, files_value: Value) -> Result<Vec<MultipartFilePart>, Error> {
368
- let files_hash = RHash::try_convert(files_value)?;
369
-
370
- let keys_array: RArray = files_hash.funcall("keys", ())?;
371
- let mut result = Vec::new();
372
-
373
- for i in 0..keys_array.len() {
374
- let key_val = keys_array.entry::<Value>(i as isize)?;
375
- let field_name = String::try_convert(key_val)?;
376
- let value = files_hash
377
- .get(key_val)
378
- .ok_or_else(|| Error::new(ruby.exception_runtime_error(), "Failed to get hash value"))?;
379
-
380
- if let Some(outer_array) = RArray::from_value(value) {
381
- if outer_array.is_empty() {
382
- continue;
383
- }
384
-
385
- let first_elem = outer_array.entry::<Value>(0)?;
386
-
387
- if RArray::from_value(first_elem).is_some() {
388
- for j in 0..outer_array.len() {
389
- let file_array = outer_array.entry::<Value>(j as isize)?;
390
- let file_data = extract_single_file(ruby, &field_name, file_array)?;
391
- result.push(file_data);
392
- }
393
- } else {
394
- let file_data = extract_single_file(ruby, &field_name, value)?;
395
- result.push(file_data);
396
- }
397
- }
398
- }
399
-
400
- Ok(result)
401
- }
402
-
403
- /// Extract a single file from a Ruby array [filename, content, content_type (optional)].
404
- pub fn extract_single_file(ruby: &Ruby, field_name: &str, array_value: Value) -> Result<MultipartFilePart, Error> {
405
- let array = RArray::from_value(array_value)
406
- .ok_or_else(|| Error::new(ruby.exception_arg_error(), "file must be an Array [filename, content]"))?;
407
-
408
- if array.len() < 2 {
409
- return Err(Error::new(
410
- ruby.exception_arg_error(),
411
- "file Array must have at least 2 elements: [filename, content]",
412
- ));
413
- }
414
-
415
- let filename: String = String::try_convert(array.shift()?)?;
416
- let content_str: String = String::try_convert(array.shift()?)?;
417
- let content = content_str.into_bytes();
418
-
419
- let content_type: Option<String> = if !array.is_empty() {
420
- String::try_convert(array.shift()?).ok()
421
- } else {
422
- None
423
- };
424
-
425
- Ok(MultipartFilePart {
426
- field_name: field_name.to_string(),
427
- filename,
428
- content,
429
- content_type,
430
- })
431
- }
432
-
433
- /// Extract an optional string from a Ruby Hash.
434
- pub fn get_optional_string_from_hash(hash: RHash, key: &str) -> Result<Option<String>, Error> {
435
- match hash.get(String::from(key)) {
436
- Some(v) if !v.is_nil() => Ok(Some(String::try_convert(v)?)),
437
- _ => Ok(None),
438
- }
439
- }
440
-
441
- /// Extract a required string from a Ruby Hash.
442
- pub fn get_required_string_from_hash(hash: RHash, key: &str, ruby: &Ruby) -> Result<String, Error> {
443
- let value = hash
444
- .get(String::from(key))
445
- .ok_or_else(|| Error::new(ruby.exception_arg_error(), format!("missing required key '{}'", key)))?;
446
- if value.is_nil() {
447
- return Err(Error::new(
448
- ruby.exception_arg_error(),
449
- format!("key '{}' cannot be nil", key),
450
- ));
451
- }
452
- String::try_convert(value)
453
- }
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
+ }