0

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.

1
  • Is this an X-Y problem? Are you sure that you need a global variable in the first place? You might be better served by describing what you're really trying to accomplish. Commented Jul 27, 2015 at 23:10

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@MPorto If that is the case, it may be a good idea to either accept this answer, or respond with your own solution and accept that.
0

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)

1 Comment

Let's just hope no-one ever changes the default scope ordering... Also, have a read-up on "race conditions".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.