I am developing a feature to track packages. So every time I create a new package I assign it a barcode_number. That is the global variable I would create. Every time I assigned that to a new package, I would increment it by one, thus ensuring that two packages would never have the same number.
2 Answers
This pattern comes to mind:
class Permanent
def self.increment
@@val ||= 0
@@val += 1
end
def self.value
@@val ||= 0
end
end
Invoke as Permanent.increment (or Permanent.value to just read the current value). Obviously you can rename the class and methods to be handier. You can make the starting value different than zero (or read it from a database or otherwise calculate it). The main point is that the class would behave as a singleton for your purposes.
1 Comment
The solution I found for this problem was that every time I need to assign a barcode number to a new package, I just look at the most recently added package, retrieve its barcode number, add one to that and assign this new number to the new package. It looks something like this:
barcode = ButtonFinishDiv.last.barcode + 1
ButtonFinishDiv.create(..., barcode: barcode)