So I want a module with a variable and access methods.
My code looks something like this
module Certificates
module Defaults
class << self
attr_accessor :address
def get_defaults
address = "something"
make_root_cert
end
def make_root_cert
blub = address
# do somthing
end
end
end
I inspected it with pry.
The result is
- Certificates::Defaults has methods called address and address=.
- If I call address in the get_defaults method it returns “something” as expected
- If I call it in make_root_cert it returns nil
I used this way of attr_accessor creation in another module and it worked fine. I hope I’m just misunderstanding the way ruby works and somebody can explain why this example doesn’t work. Maybe using the implementation details of the ruby object model.
Jeremy is right.
My findings
This seems inconsistent to me.
- If you use the expression “address” and the instance variable has not been set it returns the local variable
- If the instance variable has been set and the local variable not it returns the instance variable.
- If both have been set it returns the local variable.
On the other hand address=”test” always sets the local variable.
In your
get_defaultsmethods,addressis a local variable. To use the setter, you have to type this:That will properly call the
address=method.