From: Nasir Khan Date: 2007-06-09T04:34:42+09:00 Subject: Synchronized attr_accessor I have a fairly repetitive use case of having to define attributes and have them lock protected. I was thinking of defining a attr_accessor kind of directive but one that creates a lock protected attribute - class Module def attr_sync_accessor(*symbols) symbols.each do |symbol| str = <<-EOF def #{symbol}() if @#{symbol} @#{symbol}.synchronize { return @#{symbol} } else nil end end EOF module_eval(str) str = <<-EOF def #{symbol}=(val) if @#{symbol} @#{symbol}.synchronize { @#{symbol} = val } else @#{symbol} = val @#{symbol}.extend(MonitorMixin) end end EOF module_eval(str) end end end #-------------- Now to use it you need to require monitor so require 'monitor' class A attr_sync_accessor :hello def get hello end def set(val) self.hello = val end end irb(main):190:0* d = A.new => # irb(main):191:0> d.set "h" => "h" irb(main):192:0> d.get => "h" This works but obviously has some flaws, like for example first time creation of attribute is unprotected as is the nil check, also it does not address scope [private, protected etc.]. I am looking for suggestions on improvements to this if anyone else also finds it useful or if it is solved by someone in some other way and I have overlooked something. TIA - Nasir