On Apr 30, 9:40 am, Iki Baz Castillo <i... / aliax.net> wrote:
> 2008/4/30, Chris Hulan <chris.hu... / gmail.com>:
>
>
>
> > Why not just access param?
>
> >  class Foo
> >   def initialize
> >     @param = {}
> >   end
> >   attr_accessor :param
> >  end
>
> >  x = Foo.new
> >  x.param['key'] = 'bar'
>
> >  If you do need to override it, the Hash assignment method is []=
> >  So I think you can write:
> >  def []=(key,value)
> >  ...
>
> Because I need to give value to an attribute of a class containing the
> Hash @params, so the only way (AFAIK) is by creating an abstraction
> layer and handling the Hash @params via current class methods. This is
> my case:
>
> class Uri
>
>   # Atributes:
>   @modified   =>  true/false
>   @params => Hash
>
>    attr_accessor :modified
>
>    #what I want but it's not possible:
>    def param(name)= (value)
>       @params[name] = value
>       @modified = true
>    end
>
> end
>
> I can't do it by extending Hash class since inside Hash class I can't
> modify @modified attribute.
> Also note there are more ways than "=" to modify a Hash value:
>   @params[name].strip!   ,   .chomp!   ,   .downcase!  ......
> and I don't want to redefine all of them so I just want to allow "="
> and when it's called @modifed must be true.
>
> Hope I've explained why attr_accessor is not useful for me in this case.
>
> Thanks a lot.
>
> --
> Iki Baz Castillo
> <i... / aliax.net>

Create your own Hash subclass?

def MyBag

  def initialize(parent)
    @parent = parent
    @theBag = {}
  end

  def []=(k,v)
    @theBag[k] = v
    @parent.modified = true
  end

  def [](k)
    @theBag[k]
  end
end

class Uri
  def initialize
    @params = MyBag.new(self) #need to do this in initialize,
otherwise self is not the instance
    @modified = false
  end
  attr_accessor :modified, :params

end

Not tested, and there is most likely a more elegant way to delegate to
Hash, but you get what you pay for 9^)