I need to generate sequences of labels that look like "ABC1" and "XYZ9" -- always three letters followed by a single digit. I want both parts of the label to increment logically, and always be the exact format and length.
I started with:
sequence(:code) { |n| "ABC#{n}" }
That was fine, but after the ninth label (ABC9
) it went to (ABC10
), violating my formatting, and only producing 10 (or 9?) values.
A quick fix of using the sequence for the letters and hard-coding one digit makes my rollover problem not occur for 26^3 => 17,576
instances, which might be okay. But, I really want some variability in the digit as well. A random digit would probably be good enough...but I want all the available values.
I thought about a few somewhat kludgy ways of building the string from one or two sequences to get comprehensive values always matching the format, but they seemed clunky.
Is there an elegant way in FactoryBot to build a sequenced string with a fixed-width letter segment followed by a fixed-width numeric segment that produces all possible values?
As it turns out, the solution in a factory is sublimely simple and graceful:
FactoryBot.define do
factory :vault do
sequence(:code, 'AAA1')
end
end
This produces the following sequence:
FactoryBot.build :vault
=> #<Vault code: "AAA1">
=> #<Vault code: "AAA2">
=> #<Vault code: "AAA3">
=> #<Vault code: "AAA4">
=> #<Vault code: "AAA5">
=> #<Vault code: "AAA6">
=> #<Vault code: "AAA7">
=> #<Vault code: "AAA8">
=> #<Vault code: "AAA9">
=> #<Vault code: "AAB0">
=> #<Vault code: "AAB1">
=> #<Vault code: "AAB2">
... four hours later ...
=> #<Vault code: "ZZY7">
=> #<Vault code: "ZZY8">
=> #<Vault code: "ZZY9">
=> #<Vault code: "ZZZ0">
=> #<Vault code: "ZZZ1">
=> #<Vault code: "ZZZ2">
=> #<Vault code: "ZZZ3">
=> #<Vault code: "ZZZ4">
=> #<Vault code: "ZZZ5">
=> #<Vault code: "ZZZ6">
=> #<Vault code: "ZZZ7">
=> #<Vault code: "ZZZ8">
=> #<Vault code: "ZZZ9">
=> #<Vault code: "AAAA0">
=> #<Vault code: "AAAA1">
For my needs, I'm not concerned about the total rollover after 175,760 values.
It's also worth noting that you can start each segment wherever you like. This works just as well:
sequence(:code, 'ABC9')
FactoryBot.build :vault
=> #<Vault code: "ABC9">
=> #<Vault code: "ABD0">
=> #<Vault code: "ABD1">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With