From 9c4f37c17e41930b3e2b085861fa7c4bf71a9db6 Mon Sep 17 00:00:00 2001 From: Dirkjan Ochtman Date: Wed, 6 Sep 2017 20:03:22 +0200 Subject: Decrease coupling with Rocket in generated code --- askama/src/lib.rs | 19 ++++++++++++++++--- askama_shared/src/generator.rs | 12 ++---------- 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/askama/src/lib.rs b/askama/src/lib.rs index 7ebc5db..d56326c 100644 --- a/askama/src/lib.rs +++ b/askama/src/lib.rs @@ -289,9 +289,22 @@ pub mod iron { #[cfg(feature = "with-rocket")] pub mod rocket { extern crate rocket; - pub use self::rocket::http::{ContentType, Status}; - pub use self::rocket::request::Request; - pub use self::rocket::response::{Responder, Response}; + + use self::rocket::http::{ContentType, Status}; + use self::rocket::request::Request; + use self::rocket::response::Response; + use std::io::Cursor; + + pub use self::rocket::response::{Responder, Result}; + + pub fn respond(t: &super::Template, ext: &str) -> Result { + let rsp = t.render().map_err(|_| Status::InternalServerError)?; + let ctype = ContentType::from_extension(ext).ok_or(Status::InternalServerError)?; + Response::build() + .header(ctype) + .sized_body(Cursor::new(rsp)) + .ok() + } } fn visit_dirs(dir: &Path, cb: &Fn(&DirEntry)) -> io::Result<()> { diff --git a/askama_shared/src/generator.rs b/askama_shared/src/generator.rs index e3454b4..4590816 100644 --- a/askama_shared/src/generator.rs +++ b/askama_shared/src/generator.rs @@ -699,21 +699,13 @@ impl<'a> Generator<'a> { fn impl_responder(&mut self, state: &'a State) { self.write_header(state, "::askama::rocket::Responder<'r>", &vec!["'r"]); self.writeln("fn respond_to(self, _: &::askama::rocket::Request) \ - -> ::std::result::Result<\ - ::askama::rocket::Response<'r>, ::askama::rocket::Status> {"); - self.writeln("let rsp = self.render().map_err(\ - |_| ::askama::rocket::Status::InternalServerError)?;"); + -> ::askama::rocket::Result<'r> {"); - self.writeln("::askama::rocket::Response::build()"); - self.indent(); let ext = match state.input.path.extension() { Some(s) => s.to_str().unwrap(), None => "txt", }; - self.writeln(&format!(".header(::askama::rocket::ContentType::from_extension({:?})\ - .unwrap())", ext)); - self.writeln(".sized_body(::std::io::Cursor::new(rsp))"); - self.writeln(".ok()"); + self.writeln(&format!("::askama::rocket::respond(&self, {:?})", ext)); self.dedent(); self.writeln("}"); -- cgit