Skip to content

Instantly share code, notes, and snippets.

@durka
Last active June 5, 2018 23:30
Show Gist options
  • Save durka/c5c3693b34b4241cab19ef6adb12eb5b to your computer and use it in GitHub Desktop.
Save durka/c5c3693b34b4241cab19ef6adb12eb5b to your computer and use it in GitHub Desktop.
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