Prefer '&str' in doc examples.

This commit is contained in:
Sergio Benitez 2021-03-27 16:25:39 -07:00
parent 3045e0ac63
commit feadb4dd16
7 changed files with 47 additions and 42 deletions

View File

@ -13,7 +13,7 @@ extensibility, and speed.
#[macro_use] extern crate rocket; #[macro_use] extern crate rocket;
#[get("/<name>/<age>")] #[get("/<name>/<age>")]
fn hello(name: String, age: u8) -> String { fn hello(name: &str, age: u8) -> String {
format!("Hello, {} year old named {}!", age, name) format!("Hello, {} year old named {}!", age, name)
} }

View File

@ -26,7 +26,7 @@ fn entry_to_tests(root_glob: &LitStr) -> Result<Vec<TokenStream>, Box<dyn Error>
.replace(|c| c == '-' || c == '.', "_")) .replace(|c| c == '-' || c == '.', "_"))
.ok_or_else(|| "invalid file name")?; .ok_or_else(|| "invalid file name")?;
let ident = Ident::new(&name, root_glob.span()); let ident = Ident::new(&name.to_lowercase(), root_glob.span());
let full_path = Path::new(&manifest_dir).join(&path).display().to_string(); let full_path = Path::new(&manifest_dir).join(&path).display().to_string();
tests.push(quote_spanned!(root_glob.span() => tests.push(quote_spanned!(root_glob.span() =>
mod #ident { mod #ident {
@ -36,5 +36,9 @@ fn entry_to_tests(root_glob: &LitStr) -> Result<Vec<TokenStream>, Box<dyn Error>
)); ));
} }
if tests.is_empty() {
return Err(format!("glob '{}' evaluates to 0 files", full_glob).into());
}
Ok(tests) Ok(tests)
} }

View File

@ -272,6 +272,7 @@ Rocket makes it easy to use `async/await` in routes.
```rust ```rust
# #[macro_use] extern crate rocket; # #[macro_use] extern crate rocket;
use rocket::tokio::time::{sleep, Duration}; use rocket::tokio::time::{sleep, Duration};
#[get("/delay/<seconds>")] #[get("/delay/<seconds>")]
async fn delay(seconds: u64) -> String { async fn delay(seconds: u64) -> String {
sleep(Duration::from_secs(seconds)).await; sleep(Duration::from_secs(seconds)).await;

View File

@ -100,7 +100,7 @@ Here's a more complete route to illustrate varied usage:
# fn main() {} # fn main() {}
#[get("/hello/<name>/<age>/<cool>")] #[get("/hello/<name>/<age>/<cool>")]
fn hello(name: String, age: u8, cool: bool) -> String { fn hello(name: &str, age: u8, cool: bool) -> String {
if cool { if cool {
format!("You're a cool {} year old, {}!", age, name) format!("You're a cool {} year old, {}!", age, name)
} else { } else {
@ -173,7 +173,7 @@ previous example:
# fn main() {} # fn main() {}
#[get("/hello/<name>/<age>/<cool>")] #[get("/hello/<name>/<age>/<cool>")]
fn hello(name: String, age: u8, cool: bool) { /* ... */ } fn hello(name: &str, age: u8, cool: bool) { /* ... */ }
``` ```
What if `cool` isn't a `bool`? Or, what if `age` isn't a `u8`? When a parameter What if `cool` isn't a `bool`? Or, what if `age` isn't a `u8`? When a parameter
@ -626,13 +626,13 @@ use serde::Deserialize;
use rocket_contrib::json::Json; use rocket_contrib::json::Json;
#[derive(Deserialize)] #[derive(Deserialize)]
struct Task { struct Task<'r> {
description: String, description: &'r str,
complete: bool complete: bool
} }
#[post("/todo", data = "<task>")] #[post("/todo", data = "<task>")]
fn new(task: Json<Task>) { /* .. */ } fn new(task: Json<Task<'_>>) { /* .. */ }
``` ```
See the [JSON example] on GitHub for a complete example. See the [JSON example] on GitHub for a complete example.
@ -711,13 +711,13 @@ can easily handle the form request in Rocket as follows:
use rocket::form::Form; use rocket::form::Form;
#[derive(FromForm)] #[derive(FromForm)]
struct Task { struct Task<'r> {
complete: bool, complete: bool,
r#type: String, r#type: &'r str,
} }
#[post("/todo", data = "<task>")] #[post("/todo", data = "<task>")]
fn new(task: Form<Task>) { /* .. */ } fn new(task: Form<Task<'_>>) { /* .. */ }
``` ```
The [`Form`] type implements the `FromData` trait as long as its generic The [`Form`] type implements the `FromData` trait as long as its generic
@ -732,10 +732,10 @@ forward or failure can be caught by using the `Option` and `Result` types:
```rust ```rust
# use rocket::{post, form::Form}; # use rocket::{post, form::Form};
# type Task = String; # type Task<'r> = &'r str;
#[post("/todo", data = "<task>")] #[post("/todo", data = "<task>")]
fn new(task: Option<Form<Task>>) { /* .. */ } fn new(task: Option<Form<Task<'_>>>) { /* .. */ }
``` ```
[`Form`]: @api/rocket/form/struct.Form.html [`Form`]: @api/rocket/form/struct.Form.html
@ -760,10 +760,10 @@ replace `Form<T>` with `Form<Strict<T>>` above to get strict parsing:
use rocket::form::{Form, Strict}; use rocket::form::{Form, Strict};
# #[derive(FromForm)] struct Task { complete: bool, description: String, } # #[derive(FromForm)] struct Task<'r> { complete: bool, description: &'r str, }
#[post("/todo", data = "<task>")] #[post("/todo", data = "<task>")]
fn new(task: Form<Strict<Task>>) { /* .. */ } fn new(task: Form<Strict<Task<'_>>>) { /* .. */ }
``` ```
`Strict` can also be used to make individual fields strict while keeping the `Strict` can also be used to make individual fields strict while keeping the
@ -838,9 +838,9 @@ structure can be written as:
# use rocket::form::FromForm; # use rocket::form::FromForm;
#[derive(FromForm)] #[derive(FromForm)]
struct External { struct External<'r> {
#[field(name = "first-Name")] #[field(name = "first-Name")]
first_name: String first_name: &'r str
} }
``` ```
@ -851,10 +851,10 @@ If you want to accept both `firstName` case-insensitively as well as
# use rocket::form::FromForm; # use rocket::form::FromForm;
#[derive(FromForm)] #[derive(FromForm)]
struct External { struct External<'r> {
#[field(name = uncased("firstName"))] #[field(name = uncased("firstName"))]
#[field(name = "first_name")] #[field(name = "first_name")]
first_name: String first_name: &'r str
} }
``` ```
@ -868,11 +868,11 @@ in each instance case-insensitively, you would write:
# use rocket::form::FromForm; # use rocket::form::FromForm;
#[derive(FromForm)] #[derive(FromForm)]
struct External { struct External<'r> {
#[field(name = uncased("first-name"))] #[field(name = uncased("first-name"))]
#[field(name = uncased("first_name"))] #[field(name = uncased("first_name"))]
#[field(name = uncased("firstname"))] #[field(name = uncased("firstname"))]
first_name: String first_name: &'r str
} }
``` ```
@ -998,19 +998,19 @@ Form structs can be nested:
use rocket::form::FromForm; use rocket::form::FromForm;
#[derive(FromForm)] #[derive(FromForm)]
struct MyForm { struct MyForm<'r> {
owner: Person, owner: Person<'r>,
pet: Pet, pet: Pet<'r>,
} }
#[derive(FromForm)] #[derive(FromForm)]
struct Person { struct Person<'r> {
name: String name: &'r str
} }
#[derive(FromForm)] #[derive(FromForm)]
struct Pet { struct Pet<'r> {
name: String, name: &'r str,
#[field(validate = eq(true))] #[field(validate = eq(true))]
good_pet: bool, good_pet: bool,
} }

View File

@ -454,7 +454,7 @@ For example, given the following route:
# fn main() {} # fn main() {}
#[get("/<id>/<name>?<age>")] #[get("/<id>/<name>?<age>")]
fn person(id: Option<usize>, name: String, age: Option<u8>) { /* .. */ } fn person(id: Option<usize>, name: &str, age: Option<u8>) { /* .. */ }
``` ```
URIs to `person` can be created as follows: URIs to `person` can be created as follows:
@ -463,7 +463,7 @@ URIs to `person` can be created as follows:
# #[macro_use] extern crate rocket; # #[macro_use] extern crate rocket;
# #[get("/<id>/<name>?<age>")] # #[get("/<id>/<name>?<age>")]
# fn person(id: Option<usize>, name: String, age: Option<u8>) { /* .. */ } # fn person(id: Option<usize>, name: &str, age: Option<u8>) { /* .. */ }
// with unnamed parameters, in route path declaration order // with unnamed parameters, in route path declaration order
let mike = uri!(person: 101, "Mike Smith", Some(28)); let mike = uri!(person: 101, "Mike Smith", Some(28));
@ -495,7 +495,7 @@ error: `person` route uri expects 3 parameters but 1 was supplied
7 | let x = uri!(person: "Mike Smith"); 7 | let x = uri!(person: "Mike Smith");
| ^^^^^^^^^^^^ | ^^^^^^^^^^^^
| |
= note: expected parameters: id: Option <usize>, name: String, age: Option <u8> = note: expected parameters: id: Option <usize>, name: &str, age: Option <u8>
``` ```
Rocket also informs you of any type errors at compile-time: Rocket also informs you of any type errors at compile-time:
@ -593,7 +593,7 @@ generated.
# #[macro_use] extern crate rocket; # #[macro_use] extern crate rocket;
# #[get("/<id>/<name>?<age>")] # #[get("/<id>/<name>?<age>")]
# fn person(id: Option<usize>, name: String, age: Option<u8>) { /* .. */ } # fn person(id: Option<usize>, name: &str, age: Option<u8>) { /* .. */ }
/// Note that `id` is `Option<usize>` in the route, but `id` in `uri!` _cannot_ /// Note that `id` is `Option<usize>` in the route, but `id` in `uri!` _cannot_
/// be an `Option`. `age`, on the other hand, _must_ be an `Option` (or `Result` /// be an `Option`. `age`, on the other hand, _must_ be an `Option` (or `Result`

View File

@ -50,7 +50,7 @@ code = '''
#[macro_use] extern crate rocket; #[macro_use] extern crate rocket;
#[get("/hello/<name>/<age>")] #[get("/hello/<name>/<age>")]
fn hello(name: String, age: u8) -> String { fn hello(name: &str, age: u8) -> String {
format!("Hello, {} year old named {}!", age, name) format!("Hello, {} year old named {}!", age, name)
} }
@ -75,17 +75,17 @@ text = '''
title = "Forms? Check!" title = "Forms? Check!"
code = ''' code = '''
#[derive(FromForm)] #[derive(FromForm)]
struct Task { struct Task<'r> {
description: String, description: &'r str,
completed: bool completed: bool
} }
#[post("/", data = "<task>")] #[post("/", data = "<task>")]
fn new(task: Form<Task>) -> Flash<Redirect> { fn new(task: Form<Task<'_>>) -> Flash<Redirect> {
if task.description.is_empty() { if task.description.is_empty() {
Flash::error(Redirect::to("/"), "Cannot be empty.") Flash::error(Redirect::to(uri!(home)), "Cannot be empty.")
} else { } else {
Flash::success(Redirect::to("/"), "Task added.") Flash::success(Redirect::to(uri!(home)), "Task added.")
} }
} }
''' '''
@ -103,14 +103,14 @@ text = '''
title = "JSON, out of the box." title = "JSON, out of the box."
code = ''' code = '''
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct Message { struct Message<'r> {
contents: String, contents: &'r str,
} }
#[put("/<id>", data = "<msg>")] #[put("/<id>", data = "<msg>")]
fn update(db: &Db, id: Id, msg: Json<Message>) -> JsonValue { fn update(db: &Db, id: Id, msg: Json<Message<'_>>) -> JsonValue {
if db.contains_key(&id) { if db.contains_key(&id) {
db.insert(id, &msg.contents); db.insert(id, msg.contents);
json!({ "status": "ok" }) json!({ "status": "ok" })
} else { } else {
json!({ "status": "error" }) json!({ "status": "error" })

View File

@ -1,5 +1,5 @@
#[cfg(any(test, doctest))] rocket::internal_guide_tests!("../guide/*.md"); #[cfg(any(test, doctest))] rocket::internal_guide_tests!("../guide/*.md");
#[cfg(any(test, doctest))] rocket::internal_guide_tests!("../../../README.md"); #[cfg(any(test, doctest))] rocket::internal_guide_tests!("../../README.md");
#[macro_export] #[macro_export]
macro_rules! map { macro_rules! map {