strum icon indicating copy to clipboard operation
strum copied to clipboard

Add the `suffix` attribute

Open nixonyh opened this issue 1 year ago • 5 comments

This is similar to #296 , but instead of prefixing str infront, we add it behind:

use strum_macros::AsRefStr;

#[derive(AsRefStr)]
#[strum(prefix = "path/to/file/", suffix = ".asset")]
enum AssetTypes {
    Filename,
}

fn main() {
    println!("{}", AssetTypes::Filename.as_ref());  // prints "path/to/file/Filename.asset"
}

This could be useful for using enum types for specifying file paths, among many other things.

nixonyh avatar Nov 28 '24 04:11 nixonyh

This makes sense to me. Are you interested in working on this?

Peternator7 avatar Dec 16 '24 05:12 Peternator7

Yes! I'll give it a go then!

nixonyh avatar Dec 16 '24 06:12 nixonyh

Hiya! Are you still working on this @nixon-voxell ? If not, mind if I have a crack at this one?

amogh-dambal avatar May 10 '25 20:05 amogh-dambal

Hey @amogh-dambal sure go ahead! Sry I've been a little busy for the past month 😅.

nixonyh avatar May 11 '25 02:05 nixonyh

I've taken an initial stab at this, but the implementation has raised a couple of questions for me RE: the behavior of both prefix and suffix with the default variant attribute.

I've included a minimum reproducible example as a test in strum_tests/tests/prefix.rs:

[allow(dead_code)]
#[derive(Debug, EnumString, Display, AsRefStr)]
#[strum(prefix = "colour/")]
enum Color {
    #[strum(to_string = "RedRed")]
    Red,
    #[strum(serialize = "b", to_string = "blue")]
    Blue { hue: usize },
    #[strum(serialize = "y", serialize = "yellow")]
    Yellow,
    #[strum(default)]
    Green(String),
}

#[test]
fn prefix_green_default() {
    assert_eq!(
        String::from("green"),
        (Color::Green("green".into())).to_string()
    );

    assert_eq!(
        String::from("colour/Green"),
        (Color::Green("green".into())).as_ref()
    );
}

The docs for default say:

Applied to a single variant of an enum. The variant must be a Tuple-like variant with a single piece of data that can be create from a &str i.e. T: From<&str>. The generated code will now return the variant with the input string captured as shown below instead of failing.

and the docs for Display say:

If the enum has a strum(prefix = "some_value_"), every variant will have that prefix prepended to the serialization.

which doesn't indicate that they should conflict in this way.

Is this discrepancy between .as_ref() and .to_string() expected?

I can also submit a pull request if it'd be easier to review the MRE that way; I just have a couple more docs I'd like to update before officially submitting a pull request for review 😅.

cc: @Peternator7

amogh-dambal avatar May 11 '25 18:05 amogh-dambal