Skip to content

Commit

Permalink
issues-721 Add impl IdenStatic and AsRef<str> to #[enum_def] attr
Browse files Browse the repository at this point in the history
  • Loading branch information
AndreiOrmanji committed Apr 15, 2024
1 parent a45318c commit f4c4efc
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
21 changes: 17 additions & 4 deletions sea-query-attr/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ pub fn enum_def(args: TokenStream, input: TokenStream) -> TokenStream {
let pascal_def_names = field_names.iter().map(|field| &field.pascal);
let pascal_def_names2 = pascal_def_names.clone();
let default_names = field_names.iter().map(|field| &field.default);
let default_names2 = default_names.clone();
let import_name = Ident::new(
args.crate_name
.unwrap_or_else(|| DEFAULT_CRATE_NAME.to_string())
Expand All @@ -100,12 +101,24 @@ pub fn enum_def(args: TokenStream, input: TokenStream) -> TokenStream {
#(#pascal_def_names,)*
}

impl #import_name::IdenStatic for #enum_name {
fn as_str(&self) -> &'static str {
match self {
#enum_name::Table => stringify!(#table_name),
#(#enum_name::#pascal_def_names2 => stringify!(#default_names2)),*
}
}
}

impl #import_name::Iden for #enum_name {
fn unquoted(&self, s: &mut dyn sea_query::Write) {
write!(s, "{}", match self {
#enum_name::Table => stringify!(#table_name),
#(#enum_name::#pascal_def_names2 => stringify!(#default_names)),*
}).unwrap();
write!(s, "{}", <Self as #import_name::IdenStatic>::as_str(&self)).unwrap();
}
}

impl ::std::convert::AsRef<str> for #enum_name {
fn as_ref(&self) -> &str {
<Self as #import_name::IdenStatic>::as_str(&self)
}
}
})
Expand Down
10 changes: 9 additions & 1 deletion sea-query-attr/tests/pass/table_iden.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use sea_query::Iden;
use sea_query::{Iden, IdenStatic};
use sea_query_attr::enum_def;
use std::convert::AsRef;

#[enum_def(table_name = "HelloTable")]
pub struct Hello {
Expand All @@ -8,4 +9,11 @@ pub struct Hello {

fn main() {
assert_eq!("HelloTable".to_string(), HelloIden::Table.to_string());
assert_eq!("name".to_string(), HelloIden::Name.to_string());

assert_eq!("HelloTable", HelloIden::Table.as_str());
assert_eq!("name", HelloIden::Name.as_str());

assert_eq!("HelloTable", AsRef::<str>::as_ref(&HelloIden::Table));
assert_eq!("name", AsRef::<str>::as_ref(&HelloIden::Name));
}

0 comments on commit f4c4efc

Please sign in to comment.