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:
(EDIT: I confused myself in my own example! Not a good sign… As @proxy is a URI object it has it's own methods, changing the URI object by using it's own methods doesn't call my own proxy=
method and update the @http object)
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>
m.proxy.host = 'otherproxy.com'
p m.proxy
# => <URI: @host="otherproxy.com" @port=8080>
# But accessing a website with @http.get('http://google.com') will still travel through myproxy.com as the @http object hasn't been changed when m.proxy.host was.