0

Let's say for instance I have the following case:

module A
  module B

    def self.make
      @correlation_id ||= SecureRandom.uuid
    end

  end
end

Now, for the outside world, I only want them to be able to access correlation_id through module A:

A.correlation_id. How would I access @correlation_id from module A?

I did the following, and it worked, but had a side-effect I didn't want.

module A
  module B

    def self.make
      @correlation_id ||= SecureRandom.uuid
    end

    private

    def self.correlation_id
      @correlation_id
    end
  end

  def self.correlation_id
    A::B.correlation_id
  end
end

With that in place, after I do A::B.make, I could do A.correlation_id, but sadly I am also able to do A::B.correlation_id. How would I alleviate this issue?

1 Answer 1

1
module A
  module B
    def self.make
      @correlation_id ||= SecureRandom.uuid
    end
  end
  def self.correlation_id
    B.instance_variable_get("@correlation_id")
  end
end

For efficiency, put .freeze after "@correlation_id".

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

4 Comments

This seems a bit meta. I'll definitely do this, but is there a more standard way? Just curious :)
What you are attempting is not standard in the first place (Allowing A to access A::B's class instance variable without allowing A::B to do so is against OOP), so there is no standard way.
Why would .freeze make this more efficient?
Because the string will then be only created at parse time and reused. It is a feature introduced recently.

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.