title: Ruby: having callbacks on 'attr' objects
body: <p>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:</p>
  
  <p>(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 <code>proxy=</code> method and update the @http object)</p>
  
  <pre><code>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
  # =&gt; &lt;URI: @host="myproxy.com" @port=8080&gt;
  
  m.proxy.host = 'otherproxy.com'
  p m.proxy
  # =&gt; &lt;URI: @host="otherproxy.com" @port=8080&gt;
  # 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.
  </code></pre>