Ruby: having callbacks on 'attr' objects
Posted
by JP
on Stack Overflow
See other posts from Stack Overflow
or by JP
Published on 2010-05-25T14:49:22Z
Indexed on
2010/05/25
14:51 UTC
Read the original article
Hit count: 173
Essentially I'm wondering how to place callbacks on objects in ruby, so that when an object is changed in anyway I can automatically trigger other changes:
class MyClass
attr_reader :proxy
def proxy=(string_proxy = "")
begin
@proxy = URI.parse("http://"+((string_proxy.empty?) ? ENV['HTTP_PROXY'] : string_proxy))
@http = Net::HTTP::Proxy.new(@proxy.host,@proxy.port)
rescue
@http = Net::HTTP
end
end
end
m = MyClass.new
m.proxy = "myproxy.com:8080"
p m.proxy
# => <URI: @host="myproxy.com" @port=8080>
# However changing m.proxy will not change the @http variable, as proxy= is not being called.
# Desired functionality:
m.proxy = nil
# Now @http.class is Net::HTTP, not Net::HTTP::Proxy
© Stack Overflow or respective owner