1
  def self.current_transaction_batch_id
    @current_transaction_batch_id ||= SecureRandom.hex
    @current_transaction_batch_id
  end

Hi, I have following method that is supposed to generate and return a batch id that I need to be unique for every request. But, the issue is that this method is returning the same value through multiple request which means the variable @current_transaction_batch_id is persisting through requests.

Thanks for help in advance

4
  • Did you try to replace ||= with = ? Now assigning a new value to a variable only works when it's empty. Therefore, the value may be the same all the time. Commented May 19, 2022 at 7:20
  • @MarcinMąsior I'm calling this method at several places in the same request. If I remove ||= and use = instead, it will replace the value of the variable @current_transaction_batch_id with a new random hex. But, I need a unique Hex throughout the lifespan of my request to remain the same. Commented May 19, 2022 at 7:21
  • During the request, the controller also has the request.request_id method that has a unique uuid generated for a given request, which can be used instead of generating hex. Do you absolutely have to use SecureRandom.hex? Commented May 19, 2022 at 7:34
  • 6
    because you're setting @ variable in a class method it is a "class instance variable" and since classes are not reloaded between requests it stays the same. Commented May 19, 2022 at 7:39

1 Answer 1

2

What Alex said in the comments is correct:

The current_transaction_batch_id method is a class method. By setting the instance_variable @current_transaction_batch_id within it, you are setting it on the class, not the instance of the class. By memoizing it you are keeping it unchanged. The class is only loaded once and kept between requests, therefore the value never changes.

You'll need to change your code, so you are working on the instance, not the class:

  def current_transaction_batch_id
    @current_transaction_batch_id ||= SecureRandom.hex
  end
Sign up to request clarification or add additional context in comments.

Comments

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.