Last active
June 5, 2018 23:30
-
-
Save durka/c5c3693b34b4241cab19ef6adb12eb5b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate proc_macro; | |
extern crate syn; | |
#[macro_use] | |
extern crate quote; | |
use proc_macro::TokenStream; | |
#[proc_macro_derive(QueryParams)] | |
pub fn derive_query_params(input: TokenStream) -> TokenStream { | |
let ast: syn::DeriveInput = syn::parse(input).expect("Could not derive QueryParams struct"); | |
let name = ast.ident; | |
let f = match ast.data { | |
syn::Data::Struct(ds) => match ds.fields { | |
syn::Fields::Named(fields) => fields.named.iter().map(|f| f.ident.unwrap()) | |
,_ => panic!("{} has no named fields", name) | |
} | |
,_ => panic!("{} is not a struct", &name) | |
}; | |
let res = quote! { | |
impl QueryParams for #name { | |
fn to_hashmap(&self) -> HashMap<String, To_Sql> { | |
let params: HashMap<String, To_Sql> = HashMap::new(); | |
#( | |
if let Some(v) = self.#f { params.push(v) } | |
)* | |
params | |
} | |
} | |
}; | |
res.into() | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment