How can I generate sequence values of mixed letter characters and number digits in FactoryBot?

Viewed 247

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?

2 Answers

Just Ruby; no rails or whatever:

code = "AAA0"
20.times{ puts code.succ! }

As it turns out, the solution in a factory is sublimely simple and graceful:

sequence(:code, 'AAA1')

This produces the following sequence:

FactoryBot.build :code

 => #<Code code: "AAA1">
 => #<Code code: "AAA2">
 => #<Code code: "AAA3">
 => #<Code code: "AAA4">
 => #<Code code: "AAA5">
 => #<Code code: "AAA6">
 => #<Code code: "AAA7">
 => #<Code code: "AAA8">
 => #<Code code: "AAA9">
 => #<Code code: "AAB0">
 => #<Code code: "AAB1">
 => #<Code code: "AAB2">
... four hours later ...
 => #<Code code: "ZZY7">
 => #<Code code: "ZZY8">
 => #<Code code: "ZZY9">
 => #<Code code: "ZZZ0">
 => #<Code code: "ZZZ1">
 => #<Code code: "ZZZ2">
 => #<Code code: "ZZZ3">
 => #<Code code: "ZZZ4">
 => #<Code code: "ZZZ5">
 => #<Code code: "ZZZ6">
 => #<Code code: "ZZZ7">
 => #<Code code: "ZZZ8">
 => #<Code code: "ZZZ9">
 => #<Code code: "AAAA0">
 => #<Code 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 :code

 => #<Code code: "ABC9">
 => #<Code code: "ABD0">
 => #<Code code: "ABD1">
Related