Was there a hook in ruby that is called every time the value of a certain variable changes?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you write a C extension for Ruby, you can actually make a global variable that triggers a setter hook whenever someone sets it.
But you probably don’t want to do that because you’d have to write some C and it could be a pain to manage that.
A better strategy would be to make it so that the variable is read and set through appropriate methods. Then when the setter method is called you can do whatever you want. Here is an example that encapsulates a variable inside an object:
Similarly you could encapsulate the variable in a module or class instead of an object.